linux下多線程中的fork介紹
問題提出:
回想一下:當(dāng)一個程序只有主線程的時候調(diào)用fork,此時fork會創(chuàng)建出的子進程也會只有一條線程;
那要是把fork放入多線程的程序中呢?
我們來試驗下:
情況(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出的子進程也會創(chuàng)建自己的子線程(兩個進程:四個線程)

情況(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)建子進程,此時fork的子進程只會執(zhí)行fork之后的代碼(兩個進程:三個線程)

情況(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處于哪個線程中,fork后創(chuàng)建的子進程將以該線程作為自己的主線程,并且執(zhí)行該線程之后的代碼
到此這篇關(guān)于linux下多線程中的fork介紹的文章就介紹到這了,更多相關(guān)linux多線程fork內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Centos中TCPWrappers訪問控制實現(xiàn)
這篇文章主要介紹了Centos中TCPWrappers訪問控制實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
解決Linux可執(zhí)行文件目錄下明明存在*.so文件,但卻提示找不到
這篇文章主要介紹了解決Linux可執(zhí)行文件目錄下明明存在*.so文件,但卻提示找不到問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

