進程的5種終止方式,進程5種終止方式
概述
正常退出
從main函數返回[return]
調用exit
調用_exit
異常退出
調用abort 產生SIGABOUT訊號
由訊號終止 Ctrl+c [SIGINT]
測試[exit/_exit]
//嘗試查看該程式的列印輸出#include <unistd.h>#include <stdlib.h>#include <iostream>using namespace std;int main(){ cout << "In main, pid = " << getpid(); //去掉了endl; //原理:與終端關聯,stdout為行緩衝,在檔案中,為全緩衝; //詳細資料請參考《UNIX環境進階編程》相關章節 //exit(0);為C庫函數,詳細解釋如下 _exit(0);}
由圖可知,系統調用_exit直接陷入核心,而C語言庫函數是經過一系列的系統清理工作,再調用Linux核心的
int main(){ cout << "In main, pid = " << getpid(); fflush(stdout);//增加了重新整理緩衝區工作 _exit(0);}
總結exit與_exit區別
1)_exit是一個系統調用,exit是一個c庫函數
2)exit會執行清除I/O緩衝
3)exit會執行調用終止處理常式//終止處理常式如下
終止處理常式:atexit
#include <stdlib.h> int atexit(void (*function)(void));
測試程式:
void exitHandler1(void){ cout << "If exit with exit, the function exitHandler will be called1" << endl;}void exitHandler2(void){ cout << "If exit with exit, the function exitHandler will be called2" << endl;}int main(){ cout << "In main, pid = " << getpid() << endl; atexit(exitHandler1);//注意,先註冊的後執行 atexit(exitHandler2); exit(0);}
異常終止
void exitHandler1(void){ cout << "If exit with exit, the function exitHandler will be called1" << endl;}void exitHandler2(void){ cout << "If exit with exit, the function exitHandler will be called2" << endl;} int main(){ cout << "In main, pid = " << getpid() << endl; atexit(exitHandler1); atexit(exitHandler2); abort(); //exit(0);}