在利用linux的fork()函数创建进程时,新建的进程会继承父进程的代码段、数据段和堆栈段。不同的子进程和父进程fork()返回的值不同。利用fork产生进程时,由于迭代的关系会产生多个进程。因此需要加条件进行限制。
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t p1 = 0;
pid_t p2 = 0;
pid_t p3 = 0;
/*call fork() function*/
p1 = fork();
if(p1==-1)printf("p1 fork error\n");
p2 = fork();
if(p2==-1)printf("p2 fork error\n");
p3 = fork();
if(p3==-1)printf("p3 fork error\n");
printf("p1 = %d; p2 = %d; p3 = %d; pid = %d\n", p1, p2, p3, getpid());
}
sunxk@146:~> ./fork
p1 = 17075; p2 = 17076; p3 = 17077; pid = 17074
p1 = 17075; p2 = 17076; p3 = 0; pid = 17077
p1 = 17075; p2 = 0; p3 = 0; pid = 17079
p1 = 0; p2 = 17078; p3 = 17080; pid = 17075
p1 = 0; p2 = 17078; p3 = 0; pid = 17080
p1 = 17075; p2 = 0; p3 = 17079; pid = 17076
p1 = 0; p2 = 0; p3 = 17081; pid = 17078
p1 = 0; p2 = 0; p3 = 0; pid = 17081
由父进程直接创建4个子进程,并根据pid来确定进程。
#include <unistd.h>
int main()
{
pid_t p1 = 0;
pid_t p2 = 0;
pid_t p3 = 0;
pid_t p4 = 0;
/*call fork() function*/
p1 = fork();
if(p1==-1)printf("p1 fork error\n");
if(p1 > 0)
{
p2 = fork();
if(p2 == -1)printf("p2 fork error\n");
}
if(p2 > 0)
{
p3 = fork();
if(p3 == -1)printf("p3 fork error\n");
}
if(p3 > 0)
{
p4 = fork();
if(p4 == -1)printf("p4 fork error\n");
}
printf("p1 = %d; p2 = %d; p3 = %d; p4 = %d\n", p1, p2, p3, p4);
while(1)
{
if((p1>0)&&(p2>0)&&(p3>0)&&(p4>0))printf("It is father process!\n");
if((p1==0)&&(p2==0)&&(p3==0)&&(p4==0))printf("It is process 1!\n");
if((p1>0)&&(p2==0)&&(p3==0)&&(p4==0))printf("It is process 2!\n");
if((p1>0)&&(p2>0)&&(p3==0)&&(p4==0))printf("It is process 3!\n");
if((p1>0)&&(p2>0)&&(p3>0)&&(p4==0))printf("It is process 4!\n");
}
}
实验结果:
It is father process!
It is process 3!
It is process 2!
It is process 1!
It is process 4!
It is process 3!
It is father process!
It is process 2!
It is process 4!
It is process 1!