linux下多線程中的fork介紹
問(wèn)題提出:
回想一下:當(dāng)一個(gè)程序只有主線程的時(shí)候調(diào)用fork,此時(shí)fork會(huì)創(chuàng)建出的子進(jìn)程也會(huì)只有一條線程;
那要是把fork放入多線程的程序中呢?
我們來(lái)試驗(yàn)下:
情況(1)fork在創(chuàng)建子線程之前
代碼:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { fork(); pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; }
結(jié)果:fork出的子進(jìn)程也會(huì)創(chuàng)建自己的子線程(兩個(gè)進(jìn)程:四個(gè)線程
)
情況(2)fork在創(chuàng)建子線程之后
代碼:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); fork(); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; }
結(jié)果:創(chuàng)建子線程之后,再創(chuàng)建子進(jìn)程,此時(shí)fork的子進(jìn)程只會(huì)執(zhí)行fork之后的代碼(兩個(gè)進(jìn)程:三個(gè)線程
)
情況(3)子線程中的fork
代碼:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { fork(); printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; }
結(jié)果:
結(jié)論:
fork處于哪個(gè)線程中,fork后創(chuàng)建的子進(jìn)程將以該線程作為自己的主線程,并且執(zhí)行該線程之后的代碼
到此這篇關(guān)于linux下多線程中的fork介紹的文章就介紹到這了,更多相關(guān)linux多線程fork內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Linux下通過(guò)sed命令對(duì)kv方式的配置文件進(jìn)行修改
sed是unix下的面向字符流的編輯器,即stream editor, 它是面向行的,以行為單位進(jìn)行處理,同時(shí),sed是非交互式的,一旦執(zhí)行便要處理完整個(gè)文件。這篇文章主要介紹了Linux下通過(guò)sed命令對(duì)kv方式的配置文件進(jìn)行修改,需要的朋友可以參考下2018-11-11Ubuntu18.04通過(guò)源碼安裝Odoo14的教程
本系列文章針對(duì)Odoo 14版,從系統(tǒng)安裝,開發(fā)環(huán)境配置,代碼結(jié)構(gòu),主要功能升級(jí),源碼賞析,Anodoo對(duì)Odoo的關(guān)鍵擴(kuò)展等角度,預(yù)先給大家介紹即將在2020年發(fā)布的這一最新版本2020-02-02Centos中TCPWrappers訪問(wèn)控制實(shí)現(xiàn)
這篇文章主要介紹了Centos中TCPWrappers訪問(wèn)控制實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11apache負(fù)載均衡的安裝和實(shí)現(xiàn)方法
在負(fù)載均衡技術(shù)中,硬件設(shè)備是比較昂貴的,對(duì)于負(fù)載均衡的學(xué)習(xí)者如果不是在企業(yè)中應(yīng)用或者是學(xué)員中學(xué)習(xí),很少有機(jī)會(huì)能碰到實(shí)際操作的訓(xùn)練。所以,很多朋友都會(huì)選擇軟件方面的設(shè)置進(jìn)行研究?,F(xiàn)在我們就來(lái)介紹一下再Apache下的Tomcat負(fù)載均衡的一些使用問(wèn)題2012-10-10Linux 和Windows 安裝Git 步驟詳細(xì)介紹
這篇文章主要介紹了Linux 和Windows 安裝Git 步驟詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2017-01-01解決Linux可執(zhí)行文件目錄下明明存在*.so文件,但卻提示找不到
這篇文章主要介紹了解決Linux可執(zhí)行文件目錄下明明存在*.so文件,但卻提示找不到問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11