pythonic
pythonic

Reputation: 21605

Determine if a process exists from its Process ID

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

Answers (3)

Raghunandan sharma
Raghunandan sharma

Reputation: 1

bool checkPidRunning(pid_t pid){
    if (kill(pid, 0) == -1 && errno == ESRCH) {
            return false; // process not exist
    }else 
    return true;
}

Upvotes: 0

Slipstream
Slipstream

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

hmjd
hmjd

Reputation: 121971

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.

Upvotes: 14

Related Questions