Fork同時(shí)創(chuàng)建多個(gè)子進(jìn)程方法
第一種方法:驗(yàn)證通過
特點(diǎn):同時(shí)創(chuàng)建多個(gè)子進(jìn)程,每個(gè)子進(jìn)程可以執(zhí)行不同的任務(wù),程序 可讀性較好,便于分析,易擴(kuò)展為多個(gè)子進(jìn)程
int main(void)
{
printf("before fork(), pid = %d\n", getpid());
pid_t p1 = fork();
if( p1 == 0 )
{
printf("in child 1, pid = %d\n", getpid());
return 0; //若此處沒有return 0 p1 進(jìn)程也會(huì)執(zhí)行 pid_t p2=fork()語句
}
pid_t p2 = fork();
if( p2 == 0 )
{
printf("in child 2, pid = %d\n", getpid());
return 0; //子進(jìn)程結(jié)束,跳回父進(jìn)程
Printf("hello world\");//沒有打印
}
int st1, st2;
waitpid( p1, &st1, 0);
waitpid( p2, &st2, 0);
printf("in parent, child 1 pid = %d\n", p1);
printf("in parent, child 2 pid = %d\n", p2);
printf("in parent, pid = %d\n", getpid());
printf("in parent, child 1 exited with %d\n", st1);
printf("in parent, child 2 exited with %d\n", st2);
return 0;
}
第二種方法: 驗(yàn)證通過
特點(diǎn):同時(shí)創(chuàng)建兩個(gè)子進(jìn)程,結(jié)構(gòu)比較繁瑣,程序可讀性不好,不易擴(kuò)展
#include
#include
#include
main()
{
printf("This is parent process%d\n",getpid());
pid_t p1,p2;
if((p1=fork())==0)
{
printf("This is child_1 process%d\n",getpid());
}
Else
{
if((p2=fork())==0)
{
printf("This is child_2 process%d\n",getpid());
}
Else
{
wait(p1,NULL,0);
wait(p2,NULL,0);
printf("This is parent process%d\n",getpid());
}
}
}
第三種方法:for 循環(huán)方法
特點(diǎn):其實(shí)每次循環(huán)只是創(chuàng)建了單個(gè)進(jìn)程,并沒有同時(shí)創(chuàng)建多個(gè)進(jìn)程
#include
#include
#include
main()
{
printf("This is parent process%d\n",getpid());
pid_t p1,p2;
int i;
for(i=0;i<=2;i++)
{
if((p1=fork())==0)
{
printf("This is child_1 process%d\n",getpid());
return 0;//這個(gè)地方非常關(guān)鍵
}
wait(p1,NULL,0); //父進(jìn)程等待p1子進(jìn)程執(zhí)行后才能繼續(xù)fork其他子進(jìn)程
printf("This is parent process%d\n",getpid());
}
}
注意:標(biāo)注的 return 0 對(duì)程序結(jié)果影響很大
無 return 0 情況
#include
#include
#include
main()
{
printf("This is parent process%d\n",getpid());
pid_t p1,p2;
int i;
for(i=0;i<=2;i++)
{
if((p1=fork())==0)
{
printf("This is child_1 process%d\n",getpid());
//return 0;//這個(gè)地方非常關(guān)鍵
}
wait(p1,NULL,0);
printf("This is parent process%d\n",getpid());
}
}
結(jié)論:父進(jìn)程會(huì)生成 n(n+1)/2+1個(gè)子進(jìn)程,N 為循環(huán)次數(shù),本例中共有 7 個(gè)子進(jìn)程, 但實(shí)際上只有 3 個(gè)是父進(jìn)程產(chǎn)生的,其余都為子進(jìn)程 fork()出來的。父進(jìn)程fork了3個(gè)進(jìn)程,第一個(gè)子進(jìn)程執(zhí)行完之后又fork了2個(gè)進(jìn)程,第2個(gè)子進(jìn)程fork了1個(gè)進(jìn)程。
正確的使用Linux中的用fork()由一個(gè)父進(jìn)程創(chuàng)建同時(shí)多個(gè)子進(jìn)程 的格式如下:
int status,i;
for (i = 0; i < 10; i++)
{
? status = fork();
? if (status == 0 || status == -1) break;//每次循環(huán)時(shí),如果發(fā)現(xiàn)是子進(jìn)程就直接從創(chuàng)建子進(jìn)程的循環(huán)中跳出來,不讓你進(jìn)入循環(huán),這樣就保證了每次只有父進(jìn)程來做循環(huán)創(chuàng)建子進(jìn)程的工作
}
if (status == -1)
{
? //error
}
else if (status == 0) //每個(gè)子進(jìn)程都會(huì)執(zhí)行的代碼
{
? //sub process
}
else
{
? //parent process
}
評(píng)論