RETURN VALUE:
The atexit() function returns the value 0 if successful; otherwise, it returns a nonzero value.
EXAMPLE:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void
bye(void)
{
printf("That was all, folks\n");
}
int
main(void)
{
long a;
int i;
a = sysconf(_SC_ATEXIT_MAX);
printf("ATEXIT_MAX = %ld\n", a);
i = atexit(bye);
if (i != 0) {
fprintf(stderr, "cannot set exit function\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
I have read manual page and StackOverflow questions, but still, have three questions about atexit
:
atexit
fail, so it will return the non-zero value? please give me such a demo, thanks!bye
will not be called until exit() is called. So does it mean we can not know atexit
's return value until exit() is called? if it is, then the third question: if
expression be executed?atexit()
registers a function to be called at program exit, but it completes its execution and returns control to the calling context, without waiting for program termination. In other words it doesn't suspend program execution, if not for the time to register the function passed. The program will then resume from where atexit()
was called, and only when it will terminate for whatever reason, the registered handler will be called.
This should answer your question 2: atexit()
returns a value "immediately", not at program termination. This should also answer your question 3: exit()
is not called when you call atexit()
, and the program flow can continue as normal.
Regarding your first question, the conditions upon which atexit()
can fail depend on the particular libc implementation. In those cases a negative value will be returned and errno
will contain a code reflecting the error condition. For example, in GNU libc atexit() returns with an error if it cannot allocate an entry for the passed error function, see the __new_exitfn() source code, called internally by atexit
(source code here).