Determine if a process exists from its process id

I want to know in my program if there is a process with a specific identifier. To achieve this, I performed the following function, which checks for existence /proc/<PID>/maps. However, I notice that even if I kill the function with the given identifier, this function still returns 1. Is there a better way to achieve what I'm trying to do, and if not, then what is the problem with this code, if there is why it returns 1 when it should return 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;
}
+5
source share
2 answers

Use kill()with signal 0:

if (0 == kill(pid, 0))
{
    // Process exists.
}

From man kill:

sig 0, , - ; .

+8

, :

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;
}

!

+5

All Articles