Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 318
Alex Avatar asked Mar 11 '11 21:03

Alex


1 Answers

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
}
like image 186
Erik Avatar answered Oct 18 '22 22:10

Erik