Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if process is running in linux

Tags:

linux

bash

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?

like image 624
noMAD Avatar asked Nov 06 '12 23:11

noMAD


People also ask

How do you check if any process is running?

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.

How do I know if a process is running in the background Linux?

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.

What is running process in Linux?

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.


1 Answers

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.

like image 50
Basile Starynkevitch Avatar answered Oct 12 '22 18:10

Basile Starynkevitch