In C++ (running on Linux), want to do something like this to determine if a process is not running
bool isnotrunning(pid_t pidnr)
{
if(pidnr <= 0) return true;
if(kill(pidnr,0) == 0) return false;
return true;
}
and then in my main, I do
pid_t myPid = -1;
while(1) {
if(isnotrunning(myPID) {
myPid = fork();
if(myPid == 0) { /*Do something in child process*/ return 0; }
}
}
Basically just starting the child process again, if it has ended.
The first run in the while() works, the child process starts up, but after the end, it does not start up a second time. I can see (in terminal with pidof myApplicationName
), that it starts up (2 pid's), then it has ended (1 pid again), and I found out that kill pidOfFirstChild
does always return 0
, and not an error after the child process has ended.
What's my error? I thought that kill()
would return an error every time I call it on a non-existing pid, but apparently that's wrong...
Even after the child process exits, it continues to exist (as a so-called "zombie process") until the parent has "reaped" it by calling waitpid(2)
or one of its relatives. When it's a zombie, kill(pid, 0)
will still return 0 on many systems (including POSIX-compliant systems).
So your parent process needs to use waitpid()
to wait for the process. When waitpid()
indicates that the process has exited, you can then immediately take whatever action is appropriate, set a flag to remember that it happened, etc. This is likely a better design than trying to test for the child's existence with kill(2)
, and is also more reliable, since PIDs can be reused by the system. It'll also give you access to the child's exit status, if that is useful to you.
Note that, at least on my system, pidof
doesn't report zombie processes, so that would also explain why you didn't see it there.