How to check if a forked process is running from program c

I have the pid of a forked process. Now, from my c code (running on Linux), I have to periodically check if this process is still running or exiting. I don't want to use blocking calls like wait()

or waitpid()

. You need (preferably) a non-blocking system call that just checks if this pid works and returns the status of the child.

What's the best and easiest way to do this?

+3


source to share


3 answers


The function waitpid()

can take a parameter value in WNOHANG

order not to block. See the man page as always.



However, I'm not sure the pids are guaranteed not to be recycled by the system, which would open it up to race conditions.

+7


source


Use the parameter WNOHANG

in waitpid()

.



+1


source


kill(pid, 0);

      

This will succeed (return 0) if the PID exists. Of course, it could have existed because the original process ended and something new took its place ... it's up to you if it matters.

Instead, you can register a handler for SIGCHLD

. It will not be affected by the PID that can be reworked.

+1


source







All Articles