子進程和父進程
在父進程中通過fork()函數可以創建子進程,如果返回值==0,為子進程;否則是為父進程。子進程得到的除了代碼段是與父進程共享以外,其他所有的都是父進程的一個副本,子進程的所有資源都繼承父進程,得到父進程資源的副本,但是二者並不共享地址空間。兩個是單獨的進程,繼承了以后二者就沒有什么關聯,子進程單獨運行。采用寫時復制技術。
關於文件描述符:繼承父進程的文件描述符時,相當於調用了dup函數,父子進程共享文件表項,即共同操作同一個文件,一個進程修改了文件,另一個進程也知道此文件被修改。
父進程通過wait()和waitpid()函數可以監控子進程。
守護進程創建及詳解、deamon 、 systemd 、自定義開機自啟動
子線程和父線程
join()
join()函數是一個等待線程完成函數,主線程需要等待子線程運行結束了才可以結束。當構造線程時,入口函數的參數類型即使參數類型是引用,但是在線程中還是作為值傳遞。
#include <iostream> #include <thread> using namespace std; void func() { for(int i = -10; i > -20; i--) { cout << "from func():" << i << endl; } } int main() //主線程 { cout << "mian()" << endl; cout << "mian()" << endl; cout << "mian()" << endl; thread t(func); //子線程 t.join(); //等待子線程結束后才進入主線程 return 0; } #include <iostream> #include <thread> using namespace std; void func() { for(int i = -10; i > -20; i--) { cout << "from func():" << i << endl; } } int main() //主線程 { thread t(func); //子線程 cout << "mian()" << endl; cout << "mian()" << endl; cout << "mian()" << endl; t.join(); //等待子線程結束后才進入主線程 return 0; }
#include <iostream> #include <thread> using namespace std; void func() { for(int i = -10; i > -20; i--) { cout << "from func():" << i << endl; } } int main() //主線程 { thread t(func); //子線程 t.join(); //等待子線程結束后才進入主線程 cout << "mian()" << endl; cout << "mian()" << endl; cout << "mian()" << endl; return 0; }
detach()函數
稱為分離線程函數,使用detach()函數會讓線程在后台運行,即說明主線程不會等待子線程運行結束才結束
通常稱分離線程為守護線程(daemon threads),UNIX中守護線程是指,沒有任何顯式的用戶接口,並在后台運行的線程。這種線程的特點就是長時間運行;線程的生命周期可能會從某一個應用起始到結束,可能會在后台監視文件系統,還有可能對緩存進行清理,亦或對數據結構進行優化。另一方面,分離線程的另一方面只能確定線程什么時候結束,發后即忘(fire andforget)的任務就使用到線程的這種方式。
當構造線程時,入口函數的參數類型即使參數類型是引用,但是在線程中還是作為值傳遞。
#include <iostream> #include <thread> using namespace std; void func() { for(int i = -10; i > -20; i--) { cout << "from func():" << i << endl; } } int main() //主線程 { cout << "mian()" << endl; cout << "mian()" << endl; cout << "mian()" << endl; thread t(func); //子線程 t.detach(); //分離子線程 return 0; }
資料:
https://blog.csdn.net/qq_30242987/article/details/104579854
https://www.cnblogs.com/f-ck-need-u/p/7058920.html
https://blog.csdn.net/qq_33001647/article/details/89761733