繁体   English   中英

C 中的 fork() 和 wait()

[英]fork() and wait() in C

我正在尝试学习 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;
}

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

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) ,我会在终端上得到一个奇怪的 output :

    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  

甚至它也不会再返回。 我不明白这与wait的功能有什么关系? 或者换句话说,为什么wait会解决这个问题?

事件的顺序似乎是:

  1. shell 是您程序的父进程。 当它fork你的程序时,你的程序继承了标准流(到终端)。

  2. 你的程序fork了一个子进程,它继承了标准流(到终端)。

  3. 当您的父进程终止时, shell 通知(因为它正在wait )并向终端发出提示。

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

您会注意到 shell 在子进程终止后不会发出第二个提示。 (shell 对您的子进程一无所知。)

订单output

您获得完整的 output 行(而不是任何交错行)的事实是因为所有进程的标准流都处于面向行的模式。

但是,不能保证进程之间的顺序。 OS 调度程序可以以任何方式对它们进行排序。 您的孩子可能比父母先打印。

:O)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM