atexit 可以注册进程退出时的钩子函数,先注册的后调用
exit退出时,会返回到进程启动历程,执行进程注册的钩子函数,而_exit()和_Exit()直接返回内核。
return 语句返回时,启动历程会自动调用exit()。
见代码:
- #include <stdlib.h>
-
-
void my_exit1(void)
-
{
-
printf("my_exit1 is called.\n");
-
}
-
-
void my_exit2(void)
-
{
-
printf("my_exit2 is called.\n");
-
}
-
-
int main(int argc, char *argv[])
-
{
-
if(atexit(my_exit2) != 0)
-
printf("can't register my_exit2.\b");
-
if(atexit(my_exit1) != 0)
-
printf("can't register my_exit1.\b");
-
if(atexit(my_exit1) != 0)
-
printf("can't register my_exit1.\b");
-
printf("main is done.\n");
-
return(0);
-
}
运行结果:
main is done.
my_exit1 is called.
my_exit1 is called.
my_exit2 is called.
如果将return(0)改为_exit(0),则运行结果:
main is done.
atexit 注册的函数不会被调用。
阅读(1260) | 评论(0) | 转发(0) |