exit()函數(shù)與_exit()函數(shù)及return關(guān)鍵字的區(qū)別:
exit()和_exit()函數(shù)都可以用于結(jié)束進程,不過_exit()調(diào)用之后會立即進入內(nèi)核,而exit()函數(shù)會先執(zhí)行一些清理之后才會進入內(nèi)核,比如調(diào)用各種終止處理程序,關(guān)閉所有I/O流等,我建議直接在Linux的終端中查看man手冊,手冊的內(nèi)容是最官方的,而且不會有錯,手冊的英文是為全世界的程序員做的,所以手冊的英語不會難。
1. 實例代碼:
#include <unistd.h> void _exit(int status); #include <stdlib.h> void _Exit(int status); DESCRIPTION The function _exit() terminates the calling process "immediately". Any open file descriptors belonging to the process are closed; any children of the process are inherited by process 1, init, and the process's parent is sent a SIGCHLD signal. The value status is returned to the parent process as the process's exit status, and can be collected using one of the wait() family of calls.
這是手冊對_exit()函數(shù)的描述,意思是_exit()函數(shù)終止調(diào)用的進程,進程所有的文件描述符(在linux中一切皆文件)都被關(guān)閉, 這個進程的所有子進程將被init(最初的進程,所有的進程都是來自init進程,所有的進程都由其父進程創(chuàng)建,即init進程是所有進程的祖先!)進程領(lǐng)養(yǎng),并且這個終止的進程將向它的父進程發(fā)送一個sigchld信號。_exit()的參數(shù)status被返回給這個終止進程的父進程來作為這個終止進程的退出狀態(tài),這個退出狀態(tài)值能被wait()函數(shù)族的調(diào)用收集(就是通過wait()函數(shù)來獲得子進程的退出狀態(tài),之后wait()函數(shù)將會釋放子進程的地址空間,否則會出現(xiàn)zoom進程)。
_exit()函數(shù)是系統(tǒng)調(diào)用。會清理內(nèi)存和包括pcb(內(nèi)核描述進程的主要數(shù)據(jù)結(jié)構(gòu))在內(nèi)的數(shù)據(jù)結(jié)構(gòu),但是不會刷新流,而exit()函數(shù)會刷新流。比如exit()函數(shù)會將I/O緩沖中的數(shù)據(jù)寫出或讀入(printf()就是I/O緩沖,遇到‘/n'才會刷新,若直接調(diào)用exit()則會刷新,而_exit()則不會刷新)。
2.實例代碼:
#include <stdlib.h> void exit(int status);DESCRIPTION The exit() function causes normal process termination and the value of status & 0377 is returned to the parent (see wait(2)).
這是man手冊中對exit()函數(shù)的秒數(shù),exit()函數(shù)導(dǎo)致子進程的正常退出,并且參數(shù)status&0377這個值將被返回給父進程。exit()應(yīng)該是庫函數(shù)。exit()函數(shù)其實是對_exit()函數(shù)的一種封裝(庫函數(shù)就是對系統(tǒng)調(diào)用的一種封裝)。
3.return 不是系統(tǒng)調(diào)用,也不是庫函數(shù),而是一個關(guān)鍵字,表示調(diào)用堆棧的返回(過程活動記錄),是函數(shù)的退出,而不是進程的退出。
return函數(shù)退出,將函數(shù)的信息返回給調(diào)用函數(shù)使用,與exit()和_exit()函數(shù)有本質(zhì)區(qū)別。
4.abort()函數(shù)。
#include <stdlib.h> void abort(void);DESCRIPTION The abort() function causes abnormal program termination unless the signal SIGABRT is caught and the signal han- dler does not return. If the abort() function causes program termination, all open streams are closed and flushed. If the SIGABRT signal is blocked or ignored, the abort() function will still override it.
abort()函數(shù)用于異常退出。返回一個錯誤代碼。錯誤代碼的缺省值是3。abort()函數(shù)導(dǎo)致程序非正常退出除非sigabrt信號被捕捉到,并且信號處理函數(shù)沒有返回(即abort()函數(shù)給自己發(fā)送sigabrt信號),如果abort()函數(shù)導(dǎo)致程序終止,所有的打開的流將被關(guān)閉并且刷新。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
| 
 
 | 
新聞熱點
疑難解答
圖片精選