Linux之创建多个子进程

/***
fork_test.c
***/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
    pid_t pid;
    printf("xxxxxxxx\n");
    
    pid = fork();
    if(-1 == pid)
    {
        perror("fork error:");
        exit(1);    
    }
    else if(pid == 0)
    {
        printf("I'm child,pid = %u,ppid = %u\n",getpid(),getppid());
    }
    else
    {
        printf("I'm parent,pid = %u, ppid = %u\n",getpid(),getppid());
        sleep(1);
    }
    printf("YYYYYYYYYYY\n");
    return 0;
}

运行结果:

ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ ./fork_test

xxxxxxxx

I'm parent,pid = 2610, ppid = 2558

I'm child,pid = 2611,ppid = 2610

YYYYYYYYYYY

YYYYYYYYYYY

 

循环创建N个子进程:

使用for循环创建五个子进程:

/***
fork_test.c
***/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
    int i;
    pid_t pid;
    printf("xxxxxxxx\n");
    
    for(i = 0; i < 5; i++)
    {
        pid = fork();
        if(-1 == pid)
        {
            perror("fork error:");
            exit(1);    
        }
        else if(pid == 0)
        {
            printf("I'm child,pid = %u,ppid = %u\n",getpid(),getppid());
        }
        else
        {
            printf("I'm parent,pid = %u, ppid = %u\n",getpid(),getppid());
            sleep(1);
        }
    }
    printf("YYYYYYYYYYY\n");
    return 0;
}

运行程序后却创建了2^5-1个子进程。

问题分析:

问题解决:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
    int i;
    pid_t pid;
    printf("xxxxxxxx\n");
    
    for(i = 0; i < 5; i++)
    {
        pid = fork();
        if(pid == 0)
        {
            break;
        }
    }

    if(i < 5)
    {
        sleep(i);
        printf("I'm %d child,pid = %u\n",i+1,getpid());

    }
    else
    {
        sleep(i);
        printf("I'm parent\n");

    }
    return 0;
}

在子进程pid == 0 时直接break出来就好了。

 

运行结果:

ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ make fork_test

gcc fork_test.c -o fork_test -Wall -g

ubuntu1604@ubuntu:~/wangqinghe/C/20190805$ ./fork_test

xxxxxxxx

I'm 1 child,pid = 3157

I'm 2 child,pid = 3158

I'm 3 child,pid = 3159

I'm 4 child,pid = 3160

I'm 5 child,pid = 3161

I'm parent

转载于:https://www.cnblogs.com/wanghao-boke/p/11317403.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值