fork() 和 waitpid() 不等待 child

fork() and waitpid() not waiting for child

我在让 waitpid 工作时遇到了一些麻烦,有人可以解释一下这段代码有什么问题吗?

#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;

int main() {
    string filename_memory;
    decltype(fork()) pid;

    if (!(pid = fork())) {
        cout << "in child" << endl;
        sleep(1);
    }

    else {
        int status_child;

        do {
            waitpid(pid, &status_child, WNOHANG);
            cout << "waiting for child to finish" << endl;
        } while (!WIFEXITED(status_child));

        cout << "child finished" << endl;
    }

    return 0;
}

If wait() or waitpid() returns because the status of a child process is available, these functions shall return a value equal to the process ID of the child process for which status is reported.

If waitpid() was invoked with WNOHANG set in options, it has at least one child process specified by pid for which status is not available, and status is not available for any process specified by pid, 0 is returned. Otherwise, (pid_t)-1 shall be returned, and errno set to indicate the error.

这意味着 status_child 变量没有意义,直到 waitpid returns child.

的 pid

您可以通过应用以下更改来解决此问题:

int ret;
do {
    ret = waitpid(pid, &status_child, WNOHANG);
    cout << "waiting for child to finish" << endl;
} while (ret != pid || !WIFEXITED(status_child));

cout << "child finished" << endl;