检查两个进程的退出代码

Checking exit codes of two processes

我有这个代码:

  pid_t pid1 = fork();

  if (pid1 == 0)
  {
    //do some stuff
    if (something)
        exit(0);
    else
        exit(1);
  }
  else if (pid1 == -1)
    printf("error\n");

  pid_t pid2 = fork();

  if (pid2 == 0)
  {
    //do some stuff
    if (something)
        exit(0);
    else
        exit(1);
  }
  else if (pid2 == -1)
    printf("error\n");

//here I want to check both exit codes

子进程将 运行 并行。我需要的是检查两个退出代码是 1 还是 0。我想我可以使用这样的东西:

pid_t pid;
int status;
while( (pid = wait(&status)) > 0)
   printf("%d exit code: %d\n", pid, WEXITSTATUS(status));

我是并行编程的新手,所以我不确定这是否是正确的解决方案。是否有可能其中一个子进程在父进程到达循环之前退出,因此它不会获得退出代码?

看这里:http://linux.die.net/man/2/wait

wait() 将阻塞直到两个进程之一结束,并且 return 有关该进程的信息。您可以调用 wait() 直到没有更多 children,或者使用 waitpid 获取有关特定 PID 的信息。

所以回答你的问题 -- 你的代码看起来不错。 wait() 会为您处理竞争条件,因为它会阻止执行直到 children 之一退出(或被其他方式停止)。

如果一个进程在父进程到达wait()之前退出,它将成为一个defunct进程(或zombie进程)。这没关系,因为如果稍后调用 wait 函数,它将获得该退出代码并且僵尸进程将成功终止。

您可以使用 waitpid() 来等待特定的进程,而不是使用只等待任何进程的 wait(),这取决于其特定的 PID,因为您有等待两个进程。

pid_t waitpid(pid_t pid, int *status, int options);

The wait() system call suspends execution of the calling process until one of its children terminates. The call wait(&status) is equivalent to:

waitpid(-1, &status, 0);

The waitpid() system call suspends execution of the calling process until a child specified by pid argument has changed state. By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument, as described below. The value of pid can be:

< -1

meaning wait for any child process whose process group ID is equal to the absolute value of pid.

-1

meaning wait for any child process.

0

meaning wait for any child process whose process group ID is equal to that of the calling process.

> 0

meaning wait for the child whose process ID is equal to the value of pid.

如果一个或两个子进程在父进程第一次调用 wait() 之前退出,那么 OS 将保留退出代码 and/or 终止原因,直到父进程到达wait()。这正是 "zombie process" 的含义。