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
then
echo "Running"
else
echo "Not running"
fi
Is my if
statement wrongly used?
Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.
You can use the ps command to list all background process in Linux. Other Linux commands to obtain what processes are running in the background on Linux. top command – Display your Linux server's resource usage and see the processes that are eating up most system resources such as memory, CPU, disk and more.
Linux commands show all running processes atop command : Advanced System & Process Monitor for Linux. htop command : Interactive process viewer in Linux. pgrep command : Look up or signal processes based on name and other attributes. pstree command : Display a tree of processes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With