#include<unistd.h>
#include<iostream>
using namespace std;
int main()
{
pid_t pid;
int i=0;
for ( i = 0; i <5; i++)
{
if ((pid=fork())==0)//通过判断语句添加break,中断子进程重复创建孙进程
{
break;
}
}
if (pid>0)
{
sleep(1);
cout<<"i am is parent process."<<" my pid is :"<<getpid()<<endl;
}else
{
cout<<"i am is :"<<i<<" process"<<"->>and my pid is:"<<getpid()
<<"---my parent pid is:"<<getppid()<<endl;
}
}
i am is :0 process->>and my pid is:4857---my parent pid is:4856
i am is :1 process->>and my pid is:4858---my parent pid is:4856
i am is :2 process->>and my pid is:4859---my parent pid is:4856
i am is :3 process->>and my pid is:4860---my parent pid is:4856
i am is :4 process->>and my pid is:4861---my parent pid is:4856
i am is parent process. my pid is :4856
这里需要注意2点。
1-在循环创建子进程的过程中,为防止重复多重创建进程,所以在判断语句中添加break中断,防止子进程重复创建孙进程。
2-为了方便排序观看,所以在循环出来后的第一个if判断中添加sleep(),为了是让程序顺序挂起,打印直观。