<!--[if !supportLists]-->Ÿ <!--[endif]-->退出/终止进程
void _exit(int status) 与 void exit(int status)
这两个函数都是让进程退出, 参数status表示进程将以何种状态退出,在<stdlib.h>中预定义了一些状态,比如EXIT_SUCCESS(值为0)表示以成功状态退出,EXIT_FAILURE(值为1)表示以失败状态退出。
调用_exit函数时,其会关闭进程所有的文件描述符,清理内存以及其他一些内核清理函数,但不会刷新流(stdin, stdout, stderr ...). exit函数时在_exit函数之上的一个封装,其会调用_exit,并在调用之前先刷新流。
参考下面这段代码:
#include <stdio.h> //for printf(const char *)
#include <unistd.h> //for fork()
#include <sys/wait.h> //for wait(int *)
#include <stdlib.h> //for EXIT_SUCCESS
int main ()
{
printf("app start...\n");
if(fork() == 0)
{
printf("do something in child process ...\n");
exit(EXIT_SUCCESS);
printf("this will not been executed\n");
}
int status;
wait(&status);
printf("app end\n");
return 0;
}
上面的代码无论时用exit还是_exit输出结果都如下:
app start...
do something in child process ...
app end
这是因为stdout缓冲区是按行缓冲的,当遇到换行符时会刷新当前缓冲区,所以当进程退出前即便_exit不刷新,"do somethign in child process "这句话仍然被输出到了屏幕上。
现在我们将使用不带换行符的printf, 并且也不调用fflush之类的函数,在使用_exit试试:
#include <stdio.h> //for printf(const char *)
#include <unistd.h> //for fork()
#include <sys/wait.h> //for wait(int *)
#include <stdlib.h> //for EXIT_SUCCESS
int main ()
{
printf("app start...\n");
if(fork() == 0)
{
printf("do something in child process ...");
_exit(EXIT_SUCCESS);
printf("this will not been executed\n");
}
int status;
wait(&status);
printf("app end\n");
return 0;
}
输出结果为:
app start...
app end
如果换成exit则输出结果为:
app start...
do something in child process ...app end
void abort ()
非正常地退出进程。其会产生一个SIGABORT信号,然后使进程戛然而止,也就意味着其不会进行清理工作, 但它会刷新缓冲区。
#include <stdio.h> //for printf()
#include <unistd.h> //for fork()
#include <sys/wait.h> //for wait()
#include <stdlib.h> //for EXIT_SUCCESS
int main ()
{
printf("app start...\n");
if(fork() == 0)
{
printf("do something in child process ...");
abort();
printf("this will not been executed\n");
}
int status;
wait(&status);
printf("app end\n");
return 0;
}
输出为:
app start...
do something in child process ...app end
void atexit( void (*f) () )
at the exiting moment.如果想在进程正常结束之前干一点自定义的事情,就可以调用这个函数. 其简单地利用你传入的函数指针执行一个函数回调。
值得注意的是:其仅仅在调用exit函数结束进程或进程执行完所有代码后自然结束这两种状态下,回调函数才会被执行,也就是说如果进程是被_exit或abort结束的,则atexit函数无效
#include <stdio.h> //for printf()
#include <unistd.h> //for fork()
#include <sys/wait.h> //for wait()
#include <stdlib.h> //for EXIT_SUCCESS
void before_exit()
{
printf("1,2,3 exit!\n");
}
int main ()
{
printf("app start...\n");
if(fork() == 0)
{
printf("do something in child process ...\n");
void (*f)() = before_exit;
atexit(f);
exit(EXIT_SUCCESS);
printf("this will not been executed\n");
}
int status;
wait(&status);
printf("app end\n");
return 0;
}
输出为:
app start...
do something in child process ...
1,2,3 exit!
app end