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)文章
Apache中mod_proxy模塊的使用問(wèn)題及解決方案
配置了apache的情況,包括uap集群,配置https等場(chǎng)景下均適用,這篇文章主要介紹了Apache中mod_proxy模塊的使用,需要的朋友可以參考下2024-08-08
Apache Hive 通用調(diào)優(yōu)featch抓取機(jī)制 mr本地模式
這篇文章主要為大家介紹了Apache Hive 通用調(diào)優(yōu)featch抓取機(jī)制 mr本地模式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
在Linux環(huán)境如何將python腳本打deb包
為方便傳輸和使用Python腳本,可以將其制作成deb包。本文詳細(xì)介紹了在uos系統(tǒng)下使用debian目錄和相關(guān)文件來(lái)定制和構(gòu)建deb包,涵蓋創(chuàng)建配置文件、修改文件、設(shè)置安裝和鏈接規(guī)則等步驟,并提供了打包命令。這樣可以簡(jiǎn)化腳本的分發(fā)和安裝過(guò)程,使其更加便捷2024-09-09

