繁体   English   中英

C 中的 fork()。 我需要解释这段代码

[英]fork() in C. I need explanation on this code

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

当孩子终止时,为了能够找到孩子终止的值(使用exitreturn ),我必须使用指向 integer 的指针在 waitpid() 中传递第二个参数。所以在 integer 从调用它将包括 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 的数字。

暂无
暂无

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

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