Linux中進程退出分為正常退出和異常退出
1.正常退出(1)在main()函數中執行return
(2)調用exit()函數
(3)調用_exit()函數
2.異常退出(1)調用about()函數
(2)進程收到某個信號,而該信號使進程終止
對比
(1)exit與return
exit:一個函數,有參數。exit執行完後把控制權交給系統
return:函數執行完後的返回。return執行完後把控制權交給調用函數
(2)exit與about
exit:正常終止進程
about:異常終止進程
(3)exit與_exit
相同:都是用來終止進程的。當程序執行到exit或者_exit時,系統無條件的停止剩下的所有操作,清楚包括PCB在內的各種數據結構,並終止本進程的運行
exit中的參數exit_code為0代表進程正常終止,若為其他值表示程序執行過程中有錯誤發生
異同:exit()函數的頭文件——>stdlib.h
_exit()函數的頭文件——>unistd.h
_exit()在執行後立即返回給內核,而exit()要先執行一些清除工作,然後把控制權交給內核
調用_exit()函數時,會關閉進程所有的文件描述符,清理內存及其他一些內核清理函數,但不會刷新流(stdin,stdout,stderr等)
exit()函數是在_exit()函數之上的一個封裝,它會調用_exit()函數,並在調用之前刷新流
eg:
exit.c

Makefile

執行結果:

_exit.c

Makefile

執行結果

printf()函數是使用緩沖I/O的方式,該函數在遇到"\n"換行符時自動從緩沖區中將記錄讀出。所以,exit()將緩沖區的數據寫完後才退出,而_exit()函數直接退出
若把_exit.c中“This is the content in buffer ”改為"This is the content in buffer \n",

則結果為

若把"using _exit\n"改為"using _exit",

則結果為

本文出自 “追尋內心的聲音” 博客,請務必保留此出處http://ljy789.blog.51cto.com/10697684/1828226