c - 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);
}
解决方案
当孩子终止时,为了能够找到孩子终止的值(退出或返回),我必须将 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 的数字。
推荐阅读
- machine-learning - 提高预测算法的准确性
- asp.net-web-api2 - [Authorize] 属性如何使用 owin 令牌进行授权?
- swift - 是否可以使用 NativeScript 显示用 SwiftUI 编写的视图
- asp.net-core-2.0 - 在 Visual Studio 中自动生成 API 控制器
- ruby-on-rails - Rails 4 使用 send_data 方法下载的 excel 文件出现格式错误
- javascript - 如何使用离线 Jquery?
- jsf - 未填充 selectOneMenu
- java - 提取文件中的值并将其转换为字符串以获得更多功能
- python - 如何让 pip 代理与公司证书链一起使用?
- php - 如何在多张图片上传中同时使用 id 和 name?