fork()和wait()在c循环中?

use*_*370 2 c fork pid wait wexitstatus

我在c中有这个小程序,我试图理解它是如何工作的,它是一个简单的while循环,它使用fork()wait()在命令行上打印出几行,我已尽最大努力评论我的想法是什么事件

for (i = 1; i <= 3; i++)            /*simple while loop, loops 3 times */
{
    pid = fork();                   /*returns 0 if a child process is created */
    if(pid == 0){                   /*pid should be a 0 for first loop */
        printf("Hello!\n");         /*we print hello */
        return (i);                 /*will this return i to the parent process that called fork? */ 
    }   else {                      /*fork hasn't returned 0? */
        pid = wait(&j);             /*we wait until j is available? */
        printf("Received %d\n", WEXITSTATUS(j));   /*if available we print "received (j)" */
    }
}
Run Code Online (Sandbox Code Playgroud)

该程序应该打印:

Hello!
Received 1
Hello!
Received 2
Hello!
Received 3
Run Code Online (Sandbox Code Playgroud)

当其中一个子进程返回时i,父进程是否等待它&j?这真让我困惑,任何帮助都会非常感激.

Hra*_*ant 5

在循环的每次迭代中fork()创建一个子进程.子进程打印Hello!并返回i系统.父进程阻塞,wait()直到子进程完成. j将包含子进程返回给系统的值.

  • 应该注意的是,即使子进程返回一个`int`,只有最低有效字节可用于等待终止状态的父进程.此外,必须使用`WEXITSTATUS()`获取此值(如代码所示),但当`WIFEXITED()`返回true(代码无法执行)时,这样做是安全的. (2认同)