[英]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. 我已经写了一个bash脚本,但是它似乎不起作用。
if ps aux | grep [M]yProcessName > /dev/null
then
echo "Running"
else
echo "Not running"
fi
Is my if
statement wrongly used? 我的if
语句是否被错误使用?
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). 您不想知道某个特定进程(已知pid)是否正在运行(可以通过测试pid 1234是否存在/proc/1234/
来完成),但是是否某些进程正在运行给定命令(或给定可执行文件) )。
Notice that the kill(2) syscall can be portably used to check if a given process is running (with a 0 signal, eg kill(pid,0)
). 注意, kill(2) syscall可用于检查给定进程是否正在运行(带有0信号,例如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). 从程序内部,这是一种检查已知pid进程是否仍然存在并且正在运行(或等待)的常用方法。
You could use the pidof
command to find the processes running some executable, eg pidof zsh
to find all the zsh
processes. 您可以使用pidof
命令查找运行某些可执行文件的进程,例如pidof zsh
可以查找所有zsh
进程。 You could also use killall -s 0 zsh
您也可以使用killall -s 0 zsh
And you might be interested by the pgrep
utility and the /proc
filesystem. 您可能会对pgrep
实用程序和/proc
文件系统感兴趣。
ps aux | grep [M]yProcessName | grep -v grep
There is a solution: 有一个解决方案:
if [ "$(ps aux | grep "what you need" | awk '{print $11}')" == "grep" ]; then ... elif [ ... ]; then ... else ... fi
This works fine in Debian 6. '{print $11}' is needed, because the sytem treats grep as a process as well 这在Debian 6中很好用。因为系统也会将grep视为进程,所以需要'{print $ 11}'。
processid =$(ps aux | grep 'ProcessName' | grep -v grep| awk '{print $2}')
The above command will give you the process id. 上面的命令将为您提供进程ID。 Assign that process id to a variable and do this --> 将该进程ID分配给变量,然后执行->
if cat /proc/$processid/status | grep "State: R (running)" > /dev/null
then
echo "Running"
else
echo "Not running"
fi
Using -z to check if a string is empty or not, something like this could work: 使用-z检查字符串是否为空,可以使用以下方法:
line=$(ps aux | grep [M]yProcessName)
if [ -z "$line" ]
then
echo "Not Running"
else
echo $line > /dev/null
echo "Rinnung"
fi
On my system, ps aux | grep ProcessName
在我的系统上, ps aux | grep ProcessName
ps aux | grep ProcessName
always get a line of that grep process like: ps aux | grep ProcessName
总是获得该grep进程的一行,例如:
edw4rd 9653 0.0 0.0 4388 832 pts/1 S+ 21:09 0:00 grep --color=auto ProcessName
So, the exit status is always 0. Maybe that's why your script doesn't work. 因此,退出状态始终为0。也许这就是脚本无法正常工作的原因。
SMBD=$(pidof smbd)
if [ "$SMBD" == "" ];
then
/etc/init.d/samba start;
else
/etc/init.d/samba restart;
fi
返回0表示成功,而其他失败
kill -0 `pid`; echo $?
尝试这个
ps aux | grep [M]yProcessName | grep -v grep
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.