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;
}
Use kill()
with signal 0
:
if (0 == kill(pid, 0))
{
// Process exists.
}
From man kill
:
If sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a process ID or process group ID.
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