6

I have the pid of a forked process. Now, from my c code (running on Linux), I have to check periodically whether this process is still running or terminated. I do not want to use blocking calls like wait() or waitpid(). Need (preferably) a non-blocking system call which would just check whether this pid is still running and return the status of the child.

What is best and easiest way to do it?

Pala
  • 2,011
  • 3
  • 15
  • 17
Siddhartha Ghosh
  • 2,988
  • 5
  • 18
  • 25
  • 2
    http://stackoverflow.com/questions/9152979/check-if-process-exists-given-its-pid – 4rlekin Oct 15 '14 at 11:59
  • No, you don't have to check periodically. If you have not received a SIGCHLD, then the process is still running. You only need to check on the children when you receive SIGCHLD. – William Pursell Aug 17 '20 at 17:14

3 Answers3

14

The waitpid() function can take the option value WNOHANG to not block. See the manual page, as always.

That said, I'm not sure that pids are guaranteed to not be recycled by the system, which would open this up to race conditions.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 8
    `waitpid` will only work for children of the process calling it. And their pids will not be recycled until they've been waited for, so this is the correct way to check if your child process has terminated. – Art Oct 15 '14 at 13:10
  • without storing child pid previously this solution return only terminated child pid. To get running child's pid what can I do? sample code link https://paste.ubuntu.com/25386744/ – alhelal Aug 25 '17 at 02:25
5
kill(pid, 0);

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

You might consider instead registering a handler for SIGCHLD. That will not depend on the PID which could be recycled.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 3
    This will also succeed if the process dies/exits and some other process starts with the same pid. This is a very bad practice and shouldn't be encouraged. – Art Oct 15 '14 at 13:07
  • @Art: I explicitly acknowledged that in my answer and offered a better solution with a second explicit mention of how it could be better. To say that I have "encouraged" the racy way is a bit much, don't you think? – John Zwinck Oct 15 '14 at 13:15
  • 1
    N.B. This is safe if it's your own child process that you're testing this way because the child process won't have the pid recycled until it has been waited on, but it's still a bad practice because better system calls exist for it and eventually someone will use this method incorrectly and get wrong results. Almost all uses of a pid (other than a call to `waitpid`) are open to potentially dangerous race conditions. – Art Oct 15 '14 at 13:16
3

Use the WNOHANG option in waitpid().

Claudio
  • 10,614
  • 4
  • 31
  • 71