Can some one please tell me how to check if a unix process with a given process id is running inside a C program. I know I can call system() and use the ps command but I dont want to call the system().
-
Possible duplicate: stackoverflow.com/questions/3667486/…Axel Gneiting– Axel Gneiting2011-03-28 14:53:14 +00:00Commented Mar 28, 2011 at 14:53
-
Not a duplicate. This question is about checking for a specific process ID, that other question is about listing all processes. (Juliano's excellent answer wouldn't apply to that other question.)DevSolar– DevSolar2011-03-28 15:05:40 +00:00Commented Mar 28, 2011 at 15:05
-
@EdwinBuck please consider undeleting your correct, if not entirely portable answer (on systems where /proc is available, it would provide access to information which could aid disambiguation, and on others 'ps' has to get it's information from somewhere)Chris Stratton– Chris Stratton2013-06-21 12:36:15 +00:00Commented Jun 21, 2013 at 12:36
Add a comment
|
1 Answer
Using kill(2):
if (kill(pid, 0) == 0) {
/* process is running or a zombie */
} else if (errno == ESRCH) {
/* no such process with the given pid is running */
} else {
/* some other error... use perror("...") or strerror(errno) to report */
}
5 Comments
DevSolar
Simple. Elegant. Exhaustive. +1.
R.. GitHub STOP HELPING ICE
And also useless unless the process is a child of the calling process. PIDs can be reused as soon as a finished process is
waited on by its parent, so if a process by a given PID exists, there's no guarantee it's the process you think it is unless you're the parent (and then you already know by whether its pid was returned by a wait-family function).Terminal
@R.. PIDs can be reused but most of the implementations avoid using a recently used PID. Instead kernel keep on selecting a higher number for PID unless the number overflows.
Juliano
@R.. Then your problem is with the question, not my answer. Sachin was clear enough in that he had a process ID and wanted to check if it was running. Simple question, simple answer. You should add your concerns about race conditions and what exactly he wants to do to his question, not to my answer.
R.. GitHub STOP HELPING ICE
Fair enough. Your answer is the right answer the the question and I +1'd it as such. I do think it would be a little better if it also mentioned that the question is problematic, though.