Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 394
Siddhartha Ghosh Avatar asked Oct 15 '14 11:10

Siddhartha Ghosh


People also ask

How to check if a process is running in C#?

This tutorial will introduce the methods to check if a process is running in C#. The Process.GetProcessByName () function gets all the running processes of the same name in C#. The Process.GetProcessByName () function takes the name of the process as an input and returns an array of all the processes running by the same name.

How do I know if a process is running errno?

Use kill (pid, sig) but check for the errno status. If you're running as a different user and you have no access to the process it will fail with EPERM but the process is still alive. You should be checking for ESRCH which means No such process.

What happens when checkifprocessrunning returns false in a while loop?

Once checkIfProcessRunning returns False, it sets chromeRunning = False to exit the while loop and continue with the rest of the program. You need to determine the process name you’re checking.

How to tell if a child process is running?

If you've gotten that signal, you can call wait and see if it's the child process you're looking for. If you haven't gotten the signal, the child is still running. Obviously, if you need to do nothing unitl the child finishes, just call wait.


3 Answers

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.

like image 58
unwind Avatar answered Sep 21 '22 17:09

unwind


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.

like image 26
John Zwinck Avatar answered Sep 21 '22 17:09

John Zwinck


Use the WNOHANG option in waitpid().

like image 30
Claudio Avatar answered Sep 20 '22 17:09

Claudio