Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if process exists given its pid

Tags:

c

linux

pid

Given the pid of a Linux process, I want to check, from a C program, if the process is still running.

like image 313
Simone Avatar asked Feb 05 '12 21:02

Simone


People also ask

How do you check a process ID 1234 whether it is running or not?

For example, if the PID is 1234, you'd run ps aux | grep 1234 . This isn't a very useful command, you might as well run ps u 1234 . If you prefer to use commands, lsof -p1234 shows all the files the process has open. ps uww 1234 shows various pieces of information about process 1234 including the full command line.

How do you check if a specific process is running Linux?

You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time.


2 Answers

Issue a kill(2) system call with 0 as the signal. If the call succeeds, it means that a process with this pid exists.

If the call fails and errno is set to ESRCH, a process with such a pid does not exist.

Quoting the POSIX standard:

If sig is 0 (the null signal), error checking is performed but no signal is actually sent. The null signal can be used to check the validity of pid.

Note that you are not safe from race conditions: it is possible that the target process has exited and another process with the same pid has been started in the meantime. Or the process may exit very quickly after you check it, and you could do a decision based on outdated information.

Only if the given pid is of a child process (fork'ed from the current one), you can use waitpid(2) with the WNOHANG option, or try to catch SIGCHLD signals. These are safe from race conditions, but are only relevant to child processes.

like image 149
Blagovest Buyukliev Avatar answered Sep 16 '22 12:09

Blagovest Buyukliev


Use procfs.

#include <sys/stat.h> [...] struct stat sts; if (stat("/proc/<pid>", &sts) == -1 && errno == ENOENT) {   // process doesn't exist } 

Easily portable to

  • Solaris
  • IRIX
  • Tru64 UNIX
  • BSD
  • Linux
  • IBM AIX
  • QNX
  • Plan 9 from Bell Labs
like image 32
Janus Troelsen Avatar answered Sep 20 '22 12:09

Janus Troelsen