linux下,进程可以在退出的时候调用一些用户自定义的函数,这些函数称为终止处理函数。Linux规定最多可是设置32个这样的进程处理函数。设置是需要用到atexit函数,函数原型如下:
#include <stdlib.h>
int atexit(void (*func)(void));
由以上原型知进程终止处理函数不接受任何参数,且返回之为空。
atexit返回0,代表设置成功,返回值非0,则表示设置失败。
进程终止处理函数的调用顺序与设置时相反。
下面给出一个例子:
#include <stdio.h>
#include <stdlib.h>
/*进程终止处理函数一*/
void func1(void)
{
printf("the first exit handler/n");
}
/*进程终止处理函数二*/
void func2(void)
{
printf("the second exit handler/n");
}
int main()
{
if((atexit(func1))!=0) { /*设置第一个进程终止处理函数*/
perror("fail to set exit handler");
exit(1);
}
if((atexit(func1))!=0){ /*再次设置第一个进程终止处理函数*/
perror("fail to set exit handler");
exit(1);
}
if((atexit(func2))!=0){ /*设置第二个进程终止处理函数*/
perror("fail to set exit handler");
exit(1);
}
return 0;
}
编译运行:
alei@alei-desktop:~$ gcc atexit.c -o atexit
alei@alei-desktop:~$ ./atexit
the seconde exit handler
the first exit handler
the first exit handler
alei@alei-desktop:~$