noMAD noMAD - 1 month ago 5x
Linux Question

How to check if process is running in linux

I am trying to automatically check if a process is running or not and have to perform next steps accordingly. I had written a bash script but it doesn't seem to work.

if ps aux | grep [M]yProcessName > /dev/null
echo "Running"
echo "Not running"

Is my
statement wrongly used?


You don't want to know if a particular process (of known pid) is running (this can be done by testing if /proc/1234/ exists for pid 1234) but if some process is running a given command (or a given executable).

Notice that the kill(2) syscall can be portably used to check if a given process is running (with a 0 signal, e.g. kill(pid,0)). From inside a program, this is a common way to check that a process of known pid is still existing and running (or waiting).

You could use the pidof command to find the processes running some executable, e.g. pidof zsh to find all the zsh processes. You could also use killall -s 0 zsh

And you might be interested by the pgrep utility and the /proc filesystem.