【发布时间】:2022-01-17 07:04:29
【问题描述】:
我写了一个程序,两次调用fork(),生成三个孩子和一个父母。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int child1 = fork();
int child2 = fork();
// Check for error
if (child1 < 0 || child2 < 0) {
fprintf(stderr, "A fork failed :(\n");
exit(1);
}
// Parent Process
if (child1 > 0 && child2 > 0) {
waitpid(child1, NULL, 0);
waitpid(child2, NULL, 0);
printf("I'm the parent\n");
}
// Child B -- CONFUSION AREA --
else if (child1 > 0 && child2 == 0) {
waitpid(child1, NULL, 0); // Not waiting for process to finish
printf("I'm child B\n");
}
// Child A
else if (child1 == 0 && child2 > 0) {
waitpid(child2, NULL, 0);
printf("I'm child A\n");
}
// Child C
else if (child1 == 0 && child2 == 0) {
printf("I'm child C\n");
}
return 0;
}
我正在尝试打印出来
I'm child C
I'm child A
I'm child B
I'm the parent
但是程序会打印出来
I'm child B
I'm child C
I'm child A
I'm the parent
我很困惑为什么孩子 B 不等待 child1process 完成?
我画了一个流程树来尝试了解发生了什么,我的理解是它看起来像:
/*
Parent (15543)
child1 = 15544;
child2 = 15545
/ \
/ \
/ \
A (15544) B (15545)
child1 = 0; child1 = 15544;
child2 = 15546; child2 = 0;
/
/
/
C (15546)
child1 = 0;
child2 = 0;
*/
【问题讨论】:
-
您可能对
<threads.h>,C11 的标准化线程 API 感兴趣。
标签: c operating-system