can anyone how atexit works coz i couldnt rlly understand how it goes thanks
its lil bit confusing
can anyone how atexit works coz i couldnt rlly understand how it goes thanks
its lil bit confusing
Hey I just copied this from the GNU Ref Manual:
I imagine the purpose is to close files, network connections, child processes, save data, and take care of anything else that might otherwise be left running or in an undefined state after the main process ends. You can do something similar (and perhaps more effectively) with a signal handler.Code:#include <stdio.h> #include <stdlib.h> void bye (void) { puts ("Goodbye, cruel world...."); } int main (void) { atexit (bye); exit (EXIT_SUCCESS); }
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
Basically, it works like this:
atexit itself looks something like this:Code:// inside your C-library: ... main(); ... if (atexit_function) atexit_function(); ...
In real life it's a bit more complex, because there can be several atexit functions, so it's more like an array than a single pointer - but in essence that's how it works.Code:void (*atexit_function)(void) = NULL; void atexit(void (*func)(void)) { atexit_function = func; }
The function exit() will make the program jump to the point just after main (or something that has that effect).
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
so u just call it inside a function and it exits that function ?
but why does it run in reverse mode ?
so it just exit by that function ? or there is more to it ?Code:#include <stdio.h> #include <stdlib.h> static void double_it() { int x=2; x*=x; printf("%d",x); } int main(void) { atexit(double_it); return getchar(); }
sorry 1 more question
main returns getchar first ? or atexit doubles first ?
oh okay thanks so it the last thing the program runs ty for help i understand it now
Ok, so technically there may well be stuff that happens AFTER atexit(), but that is PURELY part of the C runtime, not something you can change. Just like the C runtime runs code BEFORE main() that you also do not have any way to influence [unless you take the C runtime source code and modify it].
As an example, after atexit(), any memory allocated through malloc() and friends may be given back to the OS (assuming the OS doesn't do this by itself).
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.