您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

C++ 中 exit()、_exit()、return 與 abort() 的本質差異

編輯:iOS 開發綜合

exit() 與 _exit()

兩者都能結束進程,差別在於收尾工作的多少:_exit() 呼叫後直接進入核心,什麼都不多做;exit() 則會先跑完一輪清理——執行各終止處理程序、關閉並刷新所有 I/O 流,之後才進入核心。查 man 手冊是最可靠的做法,內容由官方維護,英文也并不難讀。

1. _exit() 的手冊描述

#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() 立即終止呼叫它的進程;該進程所有開啟的檔案描述符被關閉(在 Linux 世界裡萬物皆檔案);它的子進程會被 init 進程收養(init 是所有進程的祖先);同時向父進程送出 SIGCHLD 訊號。參數 status 作為退出狀態回傳給父進程,父進程可用 wait() 系列呼叫收集——否則子進程會變成僵屍進程。

_exit() 屬於系統呼叫。它會清理記憶體與包括 pcb(核心描述進程的主要資料結構)在內的資料結構,但不會刷新緩衝區;而 exit() 會。舉例來說,printf() 的輸出停在 I/O 緩衝裡,遇到 '\n' 才刷新,直接呼叫 exit() 會把殘留內容寫出,_exit() 則不會——這正是兩者行為差異最容易觀察到的地方。

2. exit() 的手冊描述

#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)).

exit() 造成程序的正常結束,status & 0377 的值回傳給父進程。它是標準庫函數,本質上是對 _exit() 的一層封裝——所謂庫函數,正是對系統呼叫的包裝。

return:關鍵字,不是函數

3. return 既不是系統呼叫也不是庫函數,它是一個關鍵字,作用是從呼叫堆疊返回(也就是結束函數的活動記錄)。它結束的是函數,而不是進程。

return 把結果交回給呼叫者,與 exit()、_exit() 有本質上的區別:後兩者終結的是整個進程的生命週期。

abort():異常退出

4. abort()

#include <stdlib.h>
void abort(void);
DESCRIPTION
The abort() function causes abnormal program termination unless the signal SIGABRT is caught and the signal handler 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() 用於異常結束,回傳的錯誤碼預設為 3。它會讓程序非正常結束,唯一的例外是 SIGABRT 被捕捉且信號處理函數沒有返回——換句話說,abort() 會給自己送一個 SIGABRT。若最終導致程序終止,所有開啟的流都會被關閉並刷新。即使 SIGABRT 被阻擋或忽略,abort() 仍會強制生效。

一句話總結:return 管函數、exit() 優雅退場、_exit() 立刻走人、abort() 帶著錯誤碼硬闖出去。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved