简体   繁体   中英

fork() and waitpid() not waiting for child

I am having a bit of trouble getting waitpid to work could someone please explain what is wrong with this code?

#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.

This means that the status_child variable has no meaning until waitpid returns the pid of the child.

You can fix this by applying these changes:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM