首页 > 解决方案 > C 中的 fork()。我需要解释这段代码

问题描述

所以,我有这段 C 代码

我无法理解第二个“for”部分是关于什么的。什么时候异常终止?

有人可以启发我吗?

  #include<unistd.h>
  #include<stdio.h>
  #include <sys/wait.h>

  #define N 30

  int main() {
    pid_t pid[N];
    int i;
    int child_status;
    for (i = 0; i < N; i++) {
      pid[i] = fork();
      if (pid[i] == 0) {
        sleep(60 - 2 * i);
        exit(100 + i);
      }
    }
    for (i = 0; i < N; i++) {
      pid_t wpid = waitpid(pid[i], & child_status, 0);
      if (WIFEXITED(child_status)) {
        printf("Child%d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
      } else {
        printf("Child%d terminated abnormally\n", wpid);
      }
    }
    return (0);
  }

标签: coperating-systemfork

解决方案


当孩子终止时,为了能够找到孩子终止的值(退出返回),我必须将 waitpid() 中的第二个参数与指向整数的指针一起传递。所以在从返回的那个整数中调用它将包含 2 种类型的信息 a) 如果子项通过返回或退出很好地终止或意外停止 b) 第二种类型将具有终止值。如果我想知道来自 (a) 的信息,我需要使用宏 WIFEXITED(),如果这对我来说是真的,则 (b) 来自宏 WEXITSTATUS()。这是一个简单的例子

#include <stdio.h>
#include <stdlib.h> /* For exit() */
#include <unistd.h> /* For fork(), getpid() */
#include <sys/wait.h> /* For waitpid() */
void delay() { /* Just delay */
 int i, sum=0;
 for (i = 0; i < 10000000; i++)
 sum += i;
 printf("child (%d) exits...\n", getpid());
 exit(5); /* Child exits with 5 */
}
int main() {
 int pid, status;
 pid = fork();
 if (pid == 0) /* child */
 delay();
 printf("parent (%d) waits for child (%d)...\n", getpid(), pid);
 waitpid(pid, &status, 0);
 if (WIFEXITED(status)) /* Terminated OK? */
 printf("child exited normally with value %d\n", WEXITSTATUS(status));
 else
 printf("child was terminated abnormaly.\n");
 return 0;
}

SOS宏 WEXITSTATUS() 在子进程终止时仅返回值的 8 个最不重要的位。因此,如果子进程想通过 exit/waitpid 向其父级“说”某事,则它必须是一个不超过 255 的数字。


推荐阅读