代码之家  ›  专栏  ›  技术社区  ›  AAA

C中的fork()和wait()

  •  0
  • AAA  · 技术社区  · 4 年前

    我正在学习fork()和wait()系统调用。如果我运行此代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/wait.h>
    
    
    int main (){
    
    printf("Hi, I am the parent with pid %d \n ",getpid());
    
    int rc = fork();
    
    printf("Fork returned :   %d \n ",rc);
    
    printf("I am the process with pid %d \n ",getpid());
    
    wait(NULL);
    return 0;
    }
    

    我在终端上得到了预期的输出:

    Hi, I am the parent with pid 3639 
     Fork returned :   3640 
     I am the process with pid 3639 
     Fork returned :   0 
     I am the process with pid 3640 
    

    然而,如果我删除 wait(NULL) ,我在终端上得到一个奇怪的输出:

        Hi, I am the parent with pid 3715 
         Fork returned :   3716 
         I am the process with pid 3715 
         John@John-VirtualBox:~/Fork5$  Fork returned :   0 
         I am the process with pid 3716 
    

    我完全理解,我们使用 wait() 使父进程等待子进程结束执行,以便我们可以将其从进程表中删除并取消分配其PID。但是在这里,如果我移除 wait ,我们看到终端再次被调用:

             John@John-VirtualBox:~/Fork5$  Fork returned :   0 
             I am the process with pid 3716  
    

    甚至它也不会再回来。我不明白这和 等待 ? 或者换句话说,为什么 等待 会解决这个问题吗?

    1 回复  |  直到 4 年前
        1
  •  0
  •   Dúthomhas Rishu    4 年前

    事件的顺序似乎是:

    1. shell是程序的父进程。什么时候 fork 您的程序将继承标准流(到终端)。

    2. 你的程序 叉 这是一个孩子的过程 而且 继承标准流(到终端)。

    3. 当父进程终止时,shell会注意到(因为它是 wait 并向终端发出提示。

    4. 但是,程序的子对象尚未终止,因此在shell发出提示后,子对象将打印其输出(然后终止)。

    你会注意到外壳确实如此 不 在子对象终止后发出第二个提示。(shell对您的子进程一无所知。)

    输出顺序

    事实上你得到了 完成 输出行(而不是任何交错的)是因为所有进程的标准流都在 直线导向 模式

    然而,无法保证进程之间的顺序。操作系统调度器可以按任何方式订购。你的孩子可以在父母之前打印。

    :O)