Linux进程创建fork()函数

在利用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 <sys/types.h>  
#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!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AllenSun-1990

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值