Re: How do I check if a process is running or not?

From: Steve Kirkendall (skirkendall_at_dsl-only.net)
Date: 05/25/04


Date: Tue, 25 May 2004 08:56:06 -0700

Alvin wrote:

> Andreas wrote:
>
>> Hello Everyone
>
> [snip]
>
>> So now for my question: How do I in an easy way check if process X is
>> running or not when for example trying to start it using the control
>> application? It might already have been started using the Web GUI or
>> even at bootup?
>
> Take a look at the pidof command. I use pidof in shell scripts. If you
> want to create your own program, you can do a brute force search through:
>
> /proc/<number>
>
> The <number> is an entry for each process running; the PID of a process.
> Take a look at the cmdline file inside. It's a simple text file so you can
> to a strcmp for the programs name. Another way would be to have a program
> resolve the symbolic link, exe, in the directory.

Some other related techniques:

Have process X create a file in the /var/run directory, containing its
process id -- preferably as a string of ASCII digits, not a binary number.
To protect against the possibility that process X could die without
deleting that file, you can can make process X create a lock on the file;
if the process dies, then the lock goes away. The lock won't prevent
other processes from reading the file.

Once you know the pid for process X, you can also verify that the
process still exists by calling kill(pid, 0). If it fails with an
ESRCH error, then there is no process with that pid anymore. Any other
result (including failure with an EPERM error) indicates that there
is a process with that pid.

X11 offers an entirely different way to detect running processes: Your
application can hang a special property on the root window. Usually the
name of that property is derived from the name of the program, and its
value is the Window id of the program's main window. (Taking this a step
further: X applications often use a property on the application's main
window as a request queue. Other programs can find the window and
append their requests to the property's value. The application then
reacts to a PropertyNotify event by reading that property's value.)

Note that these X11 techniques work even if the application and the
controller are running on different computers! As long as they share
the same display, they can communicate with each other.