Checking the status of a child process in C++

Alex picture Alex · Mar 11, 2011 · Viewed 31.5k times · Source

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?

Answer

Erik picture Erik · Mar 11, 2011

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
}