目标用for循环创建三个子进程
假想:父进程一次创建一个子进程,我们让它创建三次,然后就有了三个子进程;按照这个思路进行实现,相关代码如下。
//循环创建n个子进程
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int main()
{
int i = 0;
for(i=0; i<3; i++)
{
//创建子进程
pid_t pid = fork();
if(pid<0) //fork失败的情况
{
perror("fork error");
return -1;
}
else if(pid>0)//父进程
{
cout << "father:pid=" << getpid() << " fpid=" << getppid() << endl;
//sleep(1);
}
else if(pid==0) //子进程
{
cout << "child:pid=" << getpid() << " fpid=" << getppid() << endl;
//break;
}
}
sleep(10);
return 0;
}
运行后却发现,并没有按照预想创建三个子进程,而是创建了七个;如下图
其中的道理是因为子进程也会重新创建子进程。
具体分析如下:
那么如何实现三次循环创建三个子进程而且3个子进程是兄弟关系,只需要在子进程返回的语句中,加上break,让它返回之后不做任何事。
int main()
{
int i = 0;
for(i=0; i<3; i++)
{
//创建子进程
pid_t pid = fork();
if(pid<0) //fork失败的情况
{
perror("fork error");
return -1;
}
else if(pid>0)//父进程
{
cout << "father:pid=" << getpid() << " fpid=" << getppid() << endl;
//sleep(1);
}
else if(pid==0) //子进程
{
cout << "child:pid=" << getpid() << " fpid=" << getppid() << endl;
break;
}
执行后发现创建了三个子进程,如下图: