zoukankan      html  css  js  c++  java
  • Linux之创建多个子进程

    /***
    fork_test.c
    ***/
    #include<stdio.h>
    #include<stdlib.h>
    #include<unistd.h>
    
    int main()
    {
        pid_t pid;
        printf("xxxxxxxx
    ");
        
        pid = fork();
        if(-1 == pid)
        {
            perror("fork error:");
            exit(1);    
        }
        else if(pid == 0)
        {
            printf("I'm child,pid = %u,ppid = %u
    ",getpid(),getppid());
        }
        else
        {
            printf("I'm parent,pid = %u, ppid = %u
    ",getpid(),getppid());
            sleep(1);
        }
        printf("YYYYYYYYYYY
    ");
        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
    ");
        
        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
    ",getpid(),getppid());
            }
            else
            {
                printf("I'm parent,pid = %u, ppid = %u
    ",getpid(),getppid());
                sleep(1);
            }
        }
        printf("YYYYYYYYYYY
    ");
        return 0;
    }

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

    问题分析:

    问题解决:

    #include<stdio.h>
    #include<stdlib.h>
    #include<unistd.h>
    
    int main()
    {
        int i;
        pid_t pid;
        printf("xxxxxxxx
    ");
        
        for(i = 0; i < 5; i++)
        {
            pid = fork();
            if(pid == 0)
            {
                break;
            }
        }
    
        if(i < 5)
        {
            sleep(i);
            printf("I'm %d child,pid = %u
    ",i+1,getpid());
    
        }
        else
        {
            sleep(i);
            printf("I'm parent
    ");
    
        }
        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

  • 相关阅读:
    好的Qt学习资料
    QT QMap介绍与使用
    Qt缺少调试器
    vs2012+Qt5.3.1环境添加新的ui界面的方法
    QT定时器的使用
    Qt中forward declaration of struct Ui::xxx的解决
    linux-svn命令
    如何编写Windows服务
    为你的爬虫提提速?
    Python爬虫的N种姿势
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11317403.html
Copyright © 2011-2022 走看看