我需要一个独立于平台(Linux/Unix | OSX)的shell/bash命令,该命令将确定特定进程是否正在运行.e、 g.mysqld
httpd
...
我需要一个独立于平台(Linux/Unix | OSX)的shell/bash命令,该命令将确定特定进程是否正在运行.e、 g.mysqld
httpd
...
虽然pidof
和pgrep
是确定运行什么的好工具,但不幸的是,它们在某些操作系统上都不可用.一个明确的故障保险应该使用以下内容:ps cax | grep command
The output on Gentoo Linux:
14484 ? S 0:00 apache2 14667 ? S 0:00 apache2 19620 ? Sl 0:00 apache2 21132 ? Ss 0:04 apache2
The output on OS X:
42582 ?? Z 0:00.00 (smbclient) 46529 ?? Z 0:00.00 (smbclient) 46539 ?? Z 0:00.00 (smbclient) 46547 ?? Z 0:00.00 (smbclient) 46586 ?? Z 0:00.00 (smbclient) 46594 ?? Z 0:00.00 (smbclient)
On both Linux and OS X, grep returns an exit code so it's easy to check if the process was found or not:
#!/bin/bash
ps cax | grep httpd > /dev/null
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
Furthermore, if you would like the list of PIDs, you could easily grep for those as well:
ps cax | grep httpd | grep -o '^[ ]*[0-9]*'
Whose output is the same on Linux and OS X:
3519 3521 3523 3524
The output of the following is an empty string, making this approach safe for processes that are not running:
echo ps cax | grep aasdfasdf | grep -o '^[ ]*[0-9]*'
这种方法适用于编写一个简单的空字符串测试,甚至可以遍历发现的PID.
#!/bin/bash
PROCESS=$1
PIDS=`ps cax | grep $PROCESS | grep -o '^[ ]*[0-9]*'`
if [ -z "$PIDS" ]; then
echo "Process not running." 1>&2
exit 1
else
for PID in $PIDS; do
echo $PID
done
fi
您可以通过将其保存到具有执行权限(chmod+x running)的文件(名为"running")并使用参数./running "httpd"
执行来测试它
#!/bin/bash
ps cax | grep httpd
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
WARNING!!!
请记住,您只是在解析ps ax
的输出,这意味着,正如在Linux输出中所看到的,它不仅仅是在进程上进行匹配,还包括传递给该程序的参数.我强烈建议在使用此方法时尽可能具体(例如./running "mysql"
也将匹配"mysqld"流程).我强烈建议尽可能使用which
判断完整路径.
References:
中的换行符