📜  使用fork()产生1个父级及其3个子进程

📅  最后修改于: 2021-05-28 05:05:34             🧑  作者: Mango

编程以创建四个进程(1个父级和3个子级),它们按以下顺序终止:
(a)父流程最终终止
(b)第一个孩子在父母之前和第二个孩子之后终止。
(c)第二个孩子在最后一个孩子之后和第一个孩子之前终止。
(d)第三个孩子先终止。

先决条件:fork(),

    // CPP code to create three child
    // process of a parent
    #include 
    #include 
    #include 
      
    // Driver code
    int main()
    {
        int pid, pid1, pid2;
      
        // variable pid will store the
        // value returned from fork() system call
        pid = fork();
      
        // If fork() returns zero then it
        // means it is child process.
        if (pid == 0) {
      
            // First child needs to be printed
            // later hence this process is made
            // to sleep for 3 seconds.
            sleep(3);
      
            // This is first child process
            // getpid() gives the process
            // id and getppid() gives the
            // parent id of that process.
            printf("child[1] --> pid = %d and ppid = %d\n",
                   getpid(), getppid());
        }
      
        else {
            pid1 = fork();
            if (pid1 == 0) {
                sleep(2);
                printf("child[2] --> pid = %d and ppid = %d\n",
                       getpid(), getppid());
            }
            else {
                pid2 = fork();
                if (pid2 == 0) {
                    // This is third child which is
                    // needed to be printed first.
                    printf("child[3] --> pid = %d and ppid = %d\n",
                           getpid(), getppid());
                }
      
                // If value returned from fork()
                // in not zero and >0 that means
                // this is parent process.
                else {
                    // This is asked to be printed at last
                    // hence made to sleep for 3 seconds.
                    sleep(3);
                    printf("parent --> pid = %d\n", getpid());
                }
            }
        }
      
        return 0;
    }
    

    输出:

    child[3]-->pid=50 and ppid=47
    child[2]-->pid=49 and ppid=47
    child[1]-->pid=48 and ppid=47
    parent-->pid=47
    

此代码在Linux平台上运行。

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。