從圖中可以看出,_exit 函數的作用是:直接使進程停止運行,清除其使用的內存空間,並清除其在內核的各種數據結構;exit 函數則在這些基礎上做了一些小動作,在執行退出之前還加了若干道工序。exit() 函數與 _exit() 函數的最大區別在於exit()函數在調用exit 系統調用前要檢查文件的打開情況,把文件緩衝區中的內容寫回文件。也就是圖中的“清理I/O緩衝”。
所需頭文件: exit: #include<stdlib.h>
_exit: #include<unistd.h>
函數原型:exit: void exit(int status)
_exit: void _exit(int status)
函數傳入值:status 是一個整型的參數,可以利用這個參數傳遞進程結束時的狀態。一般來說,0表示正常結束;其他的數值表示出現了錯誤,進程非正常結束。在實際編程時,父進程可以利用wait 系統調用接收子進程的返回值,從而針對不同的情況進行不同的處理。
exit()與_exit() 實例分析
printf(const char *fmt,...)函數使用的是緩衝I/O方式,該函數在遇到 "\n" 換行符時自動從緩衝區中將記錄讀出。
<代碼示例>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
pid_t result;
result = fork();
if(result<0)
perror("fork");
if(result == 0)
{
printf("This is _exit test\n");
printf("This is the content in the buffer000");
_exit(0);
}
else
{
printf("This is exit test\n");
printf("This is the content in the buffer");
exit(0);
}
return 0;
}
下面是運行結果:
結果分析:子進程中運行_exit(0)並未將Thisis the content in the buffer000 打印出來,而父進程中運行的exit(0)將Thisis the content in the buffer打印出來了。說明,exit(0)會在終止進程前,將緩衝I/O內容清理掉,所以即使printf裏面沒有 \n也會被打印出來,而_exit(0)是直接終止進程,並未將緩衝I/O內容清理掉,所以不會被打印出來。