相关函数:_exit, atexit, exit
注册终止函数:
1,on_exit
头文件:#include <stdlib.h>
定义函数:int on_exit(void (* function) (int void*), void *arg);
函数说明:on_exit()用来设置一个程序正常结束前调用的函数. 当程序通过调用exit()或从main 中返回时, 参数function 所指定的函数会先被调用, 然后才真正由exit()结束程序. 参数arg 指针会传给参数function函数, 详细情况请见范例.
返回值:如果执行成功则返回0, 否则返回-1, 失败原因存于errno 中.
范例
#include <stdlib.h>
void my_exit(int status, void *arg)
{
printf("before exit()!\n");
printf("exit (%d)\n", status);
printf("arg = %s\n", (char*)arg);
}
main()
{
char * str = "test";
on_exit(my_exit, (void *)str);
exit(1234);
}
执行:
before exit()! exit (1234) arg = test
2,_onexit()
c++中_onexit使用方法
- //以下理解如有错误请指正,谢谢!
- // Author: sky
- // Date: 2011.10.4
- // Content: _onexit
- ///
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- int func1();
- //_onexit 使用方法 函数必须是 带有int类型返回值的无参数函数
- //_onexit 包含在cstdlib中 原始是c语言中的库函数
- int main(int argc,char * argv[])
- {
- _onexit(func1);//无论函数放到main中哪个位置都是最后执行
- cout<<"this is the first one"<<endl;
- cout<<"this"<<endl;
- }
- int func1()
- {
- cout<<"this executed at last time"<<endl;
- return 0;
- }
3,atexit
atexit()函数
函数名: atexit
头文件:#include<stdlib.h>
功 能: 注册终止函数(即main执行结束后调用的函数)
用 法: int atexit(void (*func)(void));
注意:按照ISO C的规定,一个进程可以登记多达32个函数,这些函数将由exit自动调用。atexit()注册的函数类型应为不接受任何参数的void函数,exit调用这些注册函数的顺序与它们 登记时候的顺序相反。同一个函数如若登记多次,则也会被调用多次。
程序例:
#include <stdio.h>
#include <stdlib.h>
void exit_fn1(void){printf("Exit function #1 called\n");}
void exit_fn2(void){printf("Exit function #2 called\n");}
int main(void){
/* post exit function #1 */
atexit(exit_fn1);
/* post exit function #2 */
atexit(exit_fn2);
return 0;
}
输出:
Exit function #2 called
Exit function #1 called
4,进程的终止方式:
有8种方式使进程终止,其中前5种为正常终止,它们是
1:从 main 返回
2:调用 exit
3:调用 _exit 或 _Exit
4:最后一个线程从其启动例程返回
5:最后一个线程调用 pthread_exit
异常终止有3种,它们是
6:调用 abort
7:接到一个信号并终止
8:最后一个线程对取消请求做出响应
#include <stdlib.h>
void exit (int status);
void _Exit (int status);
#include <unistd.h>
void _exit (status);
其中调用 _exit,_Exit 都不会调用终止程序
异常终止也不会。
获取更多帮主请关注小程序