pidof命令获取不到程序的pid

2023.08.25

问题形容

有一个性能,须要监控某个过程是否运行,如果因为某些起因没在运行(如异样挂死),则执行某个脚本,重新启动零碎。很简略那的一个性能,三下五除二写了一个脚本:

#!/bin/bashall_process_pid=(`pidof xxxx`)process_num=${all_process_pid[*]}if [ ${process_num}  -eq 1 ];then    echo "normal"else    echo "unnormal"fiexit

运行后,很完满,能够失常工作。然而在运行了一段时间后,总是发现零碎莫名微妙地重启,查看日志发现被监控的xxxx过程总是异样退出,因此会重启零碎。然而这个过程个别状况下比较稳定,不会那么频繁的挂死。但为了确定问题,就在监控脚本中加了一些调试信息,打印出现异常时候所有的过程。当呈现问题的时候,发现这个过程其实是存在的,通过ps能够看到这个过程正则运行,但通过pidof取得的过程却为空,基本上判断是pidof未找到过程ID导致的,可为什么pidof未找到呢?查问材料后发现,pidof默认状况下,不能列出zombie和I/O waiting状态的过程。通过pidof -h能够看到有个-z选项能够列出zombie和I/O waiting状态的过程。

[root@probe: ~]$ pidof  -hpidof usage: [options] <program-name> -c           Return PIDs with the same root directory -d <sep>     Use the provided character as output separator -h           Display this help text -n           Avoid using stat system function on network shares -o <pid>     Omit results with a given PID -q           Quiet mode. Do not display output -s           Only return one PID -x           Return PIDs of shells running scripts with a matching name -z           List zombie and I/O waiting processes. May cause pidof to hang.

但这个-z选项可能会导致pidof异样。
须要留神的是,不是每个发行的操作系统中的pidof命令都有-z选项,比方我目前应用的fedora workstation 38版本中,pidof就没有-z选项。

 [zy@fedora ~]$ pidof -Vpidof from procps-ng 3.3.17[zy@fedora ~]$ pidof -hUsage: pidof [options] [program [...]]Options: -s, --single-shot         return one PID only -c, --check-root          omit processes with different root -q,                       quiet mode, only set the exit code -w, --with-workers        show kernel workers too -x                        also find shells running the named scripts -o, --omit-pid <PID,...>  omit processes with PID -S, --separator SEP       use SEP as separator put between PIDs -h, --help     display this help and exit -V, --version  output version information and exit

## 解决方案
问题既然曾经明确,就比拟好批改了。因为pidof应用-z选项存在危险,且pidof命令在不同的操作系统中参数不雷同,当软件运行在不反对-z选项的操作系统上会有问题,因而决定应用其它命令判断。应用ps和grep组合进行判断。

参考资料

https://forums.linuxmint.com/viewtopic.php?t=335764