what is the purpose of atexit function?
I know when the address of the function is passed to atexit
function,
#include <stdlib.h>
int atexit(void (*func) void));
However, what is the purpose of using atexit
function?
Does verbal meaning itself 'exit' r开发者_高级运维elate to atexit
function?
atexit
would be used for some code that you want to execute when the application terminates, regardless of where it was exited from. One example would be an application-wide logger. You would call atexit(flush_log)
, so when the application exits, the log will be flushed, without the developer having to remember to flush it.
Yes, atexit
is related to exit
.
exit
can call functions which are automatically called before a program exits. These functions are called exit handlers and are registered by calling atexit
function.
#include<stdio.h>
main(void) {
atexit(func);
}
func(void)
{
...
}
#include<stdlib.h>
int atexit(void (*func)(void));
The above declaration says that we pass the address of a function as the argument to atexit
. When this function is called, it is not passed any arguments and is not expected to return a value. The exit function called these functions in reverse order of their registration. Each function is called as many times as they registered.
精彩评论