exit() 所需头文件:
#include <stdlib.h>
exit() 函数原型:
void exit( int status )
_exit() 所需头文件:
#include <unistd.h>
_exit() 函数原型:
void _exit( int status )
status 参数:
status 是一个整型的参数,可以利用这个参数传递进程结束后的状态。一般来说,0 表示正常结束;其他的数值表示出现了错误,进程非正常结束。
在实际编程时,可以用 wait() 系统调用接收子进程的返回值,从而针对不同的情况进行不同的处理。
由于历史原因,exit() 函数总是执行一个标准 I/O 库的清理关闭操作:为所有打开流调用 fclose() 函数,这样会造成所有缓冲的输出数据都被冲洗(缓冲中的数据被冲洗出,这些数据都被写到文件上)。
_exit() 和 _Exit() 会立即进入内核,exit() 像上面所说的要先执行一些清理操作(包括调用执行各终止处理程序,关闭所有标准 I/O 等)。
_exit() 会立即终止进程,与此同时也会将关闭掉属于它的所有已打开的文件描述符,它的子进程会被1号进程即 init 接管,其父进程会收到 SIGCHLD 信号。
_Eexit() 等价于 _exit() 。
比较 exit() 和 _exit() :
1、使用 exit() :
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Using exit....\n");
printf("This is the content in buffer\n");
exit(0);
}
运行及输出: beyes@linux-beyes:~/C/base> ./exit.exe
Using exit....
This is the content in buffer
2、使用 _exit()
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <unistd.h>
int main()
{
printf("Using exit....\n");
printf("This is the content in buffer");
_exit(0);
}
运行及输出: beyes@linux-beyes:~/C/base> ./exit.exe
Using exit....
beyes@linux-beyes:~/C/base> cat exit.c
由上可见,在使用 _exit() 函数时,“This is the content in buffer" 这句话并没有得到输出,这是因为这句话还在缓冲中就用了 _exit() 函数。
值得注意的是:如果程序2中的 printf("This is the content in buffer");语句改写成:
printf("This is the content in buffer\n");
那么,即使调用了 _exit() ,则要打印的内容也能够得到输出,这是因为使用了换行符 '\n' 的缘故,使用换行符,意味着提示函数在执行完时把缓冲区中的内容写到文件里。 这种行为成为“行缓冲”,关于“行缓冲”可参考:http://www.groad.net/bbs/read.php?tid-3582.html |