Reputation: 21605
I want to know in my program if a process with a certain ID exists. I implemented the following function to achieve that, which checks if /proc/<PID>/maps
exist. However, I notice that even If I kill a function with a given ID, this function still returns 1. Is there any better way of achieving what I'm trying to do and if not what is the problem with this code if any, why is it returning 1 when it should be returning 0.
int proc_exists(pid_t pid)
{
stringstream ss (stringstream::out);
ss << dec << pid;
string path = "/proc/" + ss.str() + "/maps";
ifstream fp( path.c_str() );
if ( !fp )
return 0;
return 1;
}
Upvotes: 7
Views: 14261
Reputation: 1
bool checkPidRunning(pid_t pid){
if (kill(pid, 0) == -1 && errno == ESRCH) {
return false; // process not exist
}else
return true;
}
Upvotes: 0
Reputation: 14762
To overcome the possibility of the process existing as zombie, I used the following:
bool is_pid_running(pid_t pid) {
while(waitpid(-1, 0, WNOHANG) > 0) {
// Wait for defunct....
}
if (0 == kill(pid, 0))
return 1; // Process exists
return 0;
}
It works for me!
Upvotes: 8