问题描述
我是 C 中多处理的新手。我正在使用 fork
创建一个子进程。
现在我想检查我的孩子是否已经结束(所以我可以继续下一步)。
我试图检查 /proc/${my child pid}/
是否存在,但我意识到除非我调用 waitpid
,否则它将永远作为僵尸存在。
这是一些代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
int child() {
sleep(5); // do some work here,cost a few seconds.
return 0;
}
bool check_if_child_died(int id) {
// how to complete this function?
}
int main() {
printf("BEFORE\n");
int id = fork();
if (id == -1) { return -1; }
if (id != 0) {
// father.
printf("FATHER STARTED.\n");
} else {
// child
child();
printf("CHILD END.\n");
return 0;
}
while (true) {
if (check_if_child_died(id)) {
printf("CHILD ENDED!\n");
break;
}
sleep(1); // some other work costs time here.
}
printf("END.\n");
return 0;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)