Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a process exists from its Process ID

Tags:

c++

linux

gcc

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;
}
like image 490
pythonic Avatar asked Sep 26 '12 12:09

pythonic


1 Answers

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.

like image 94
hmjd Avatar answered Oct 12 '22 10:10

hmjd