【问题标题】:fork() in C. I need explanation on this codeC 中的 fork()。我需要解释这段代码
【发布时间】:2023-03-15 09:01:01
【问题描述】:

所以,我有这段 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);
  }

【问题讨论】:

  • 我的建议是从正确缩进代码开始。没有适当的缩进就很难掌握它的结构,我想对于初学者来说比对我来说更难......
  • 当它收到信号时它会“异常”终止。见here。因此,在您的示例中,我希望 all 孩子能够正常退出,但是如果您要手动将 SIGKILL 发送给其中一个孩子(使用 kill -9 &lt;pid&gt;),那么您会看到“异常终止”消息。
  • 我在下面写了一些解释,如果这对你有帮助,请在下面的帖子中告诉我

标签: c operating-system fork


【解决方案1】:

当孩子终止时,为了能够找到孩子终止的值(使用 exitreturn),我必须将第二个参数放入带有指向整数的指针的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 的数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多