在 Debian 中监控进程

aba*_*ihi 5 shell monitoring debian services

我想创建一个服务来监视某个进程的存在。我写了以下shell脚本:

#!/bin/sh
while :
do
w=`ps u -A | grep -P ".+Sl.+/usr/local/MySource/endpoint" -c`
sleep 10
if [ $w -lt 2 ] 
then
echo 0 > /sys/class/leds/alix\:2/brightness
killall -9 /usr/local/MySource/endpoint
nohup /usr/local/MySource/endpoint &> /dev/null &
last_endpoint_m=`date`
echo $last_endpoint_m > /tmp/endpoint_msleep
echo $w >> /tmp/endpoint_msleep
else
echo 1 > /sys/class/leds/alix\:2/brightness
fi
sleep 10
done
Run Code Online (Sandbox Code Playgroud)

如果进程存在,脚本将关闭我机器上的 LED 并启动进程。LED 应该ON在进程运行时亮起。

然后,我通过将以下行添加到以下行来运行此脚本/etc/rc.local

nohup /usr/local/MyTools/additions/XR50_endpoint_m &> /dev/null &
Run Code Online (Sandbox Code Playgroud)

当我运行时ps,我发现XR50_endpoint_m &进程在那里。

我的机器是运行 Debian 的资源有限(嵌入式)的 ALIX 板。

问题是:
变量$w始终为零(我从输出文件中验证了这一点/tmp/endpoint_msleep)。尽管该进程存在并且脚本运行良好,但如果我手动运行它 ( $w=2)!

您认为原因是什么,监控流程的最佳方法是什么?

ter*_*don 5

它失败了,因为你运行ps u. 来自man ps

u 显示面向用户的格式。

这意味着ps只会列出当前用户拥有的进程。当您手动运行脚本时,该用户就是您,因此您的进程会正确列出。

(正如@Gilles 非常正确地指出的那样,使用-Awill 会导致打印所有进程,因此解释是错误的。pgrep不过还是更好)。


无论如何,更好的方法是使用pgrep

   pgrep,  pkill  - look up or signal processes based on
   name and other attributes
Run Code Online (Sandbox Code Playgroud)

改变

w=`ps u -A | grep -P ".+Sl.+/usr/local/MySource/endpoint" -c` 
Run Code Online (Sandbox Code Playgroud)

w=`pgrep -c endpoint`
Run Code Online (Sandbox Code Playgroud)