10

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().

3
  • Possible duplicate: stackoverflow.com/questions/3667486/… Commented 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.) Commented 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) Commented Jun 21, 2013 at 12:36

1 Answer 1

31

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 */
}
Sign up to request clarification or add additional context in comments.

5 Comments

Simple. Elegant. Exhaustive. +1.
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).
@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.
@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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.