Search code examples
c++forkparentwait

Checking the status of a child process in C++


I have a program that uses fork() to create a child process. I have seen various examples that use wait() to wait for the child process to end before closing, but I am wondering what I can do to simply check if the file process is still running.

I basically have an infinite loop and I want to do something like:

if(child process has ended) break;

How could I go about doing this?


Solution

  • Use waitpid() with the WNOHANG option.

    int status;
    pid_t result = waitpid(ChildPID, &status, WNOHANG);
    if (result == 0) {
      // Child still alive
    } else if (result == -1) {
      // Error 
    } else {
      // Child exited
    }