Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change atexit behavior based on program status

Tags:

c

atexit

I am trying register one function with atexit () that will print different messages based off of the current status of the program. I know that when you register the function with atexit you cannot pass an argument.

So, how can you pass the program status, say an integer, and make that function print different statements?

I know that I can register multiple functions, but I have to only use one.

like image 617
Kevin Gardenhire Avatar asked Jun 17 '26 17:06

Kevin Gardenhire


1 Answers

Instead of using atexit, make use of the on_exit function which takes the status passed into exit() as one argument, and a void * that you can pass in.

int on_exit(void (*function)(int , void *), void *arg);

The on_exit() function registers the given function to be called at normal process termination, whether via exit(3) or via return from the program's main(). The function is passed the status argument given to the last call to exit(3) and the arg argument from on_exit().

The same function may be registered multiple times: it is called once for each registration. When a child process is created via fork(2), it inherits copies of its parent's registrations. Upon a successful call to one of the exec(3) functions, all registrations are removed.

like image 121
Christian Gibbons Avatar answered Jun 19 '26 06:06

Christian Gibbons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!