Determine programmatically if a program is running

Viewed 59341

In C, how can I find out programmatically if a process is already running on Linux/Ubuntu to avoid having it start twice? I'm looking for something similar to pidof.

4 Answers

There are ways to avoid /proc usage (and there might be good reasons to do so, e.g. /proc might not be installed at all, and/or it might have been symlinked to something deceptive, or that pid has been hidden in /proc). Granted, the below method doesn't look that good, I wish there were a proper API for that!

Anyway, section 1.9 of a 1997 Unix programming FAQ says:

Use kill() with 0 for the signal number. There are four possible results from this call:

  • kill() returns 0

    This implies that a process exists with the given PID, and the system would allow you to send signals to it. It is system-dependent whether the process could be a zombie.

  • kill() returns -1, errno == ESRCH

    Either no process exists with the given PID, or security enhancements are causing the system to deny its existence. (On some systems, the process could be a zombie.)

  • kill() returns -1, errno == EPERM

    The system would not allow you to kill the specified process. This means that either the process exists (again, it could be a zombie) or draconian security enhancements are present (e.g. your process is not allowed to send signals to anybody).

  • kill() returns -1, with some other value of errno

    You are in trouble!

The most-used technique is to assume that success or failure with EPERM implies that the process exists, and any other error implies that it doesn't.

Related