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?
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.
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.
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.
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.
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.
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.
Use the WNOHANG
option in waitpid()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With