如何检查我的子进程是否在 Linux 中结束?

问题描述

我是 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 (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...