gpt4 book ai didi

Linux/Unix命令确定进程是否正在运行?

转载 作者:IT老高 更新时间:2023-10-28 12:24:36 24 4
gpt4 key购买 nike

我需要一个独立于平台的 (Linux/Unix|OSX) shell/bash 命令来确定特定进程是否正在运行。例如mysqld, httpd...最简单的方法/命令是什么?

最佳答案

虽然 pidofpgrep 是确定正在运行什么的好工具,但遗憾的是,它们在某些操作系统上都不可用。一个明确的故障保险是使用以下内容: ps cax | grep 命令

Gentoo Linux 上的输出:

14484 ?        S      0:00 apache214667 ?        S      0:00 apache219620 ?        Sl     0:00 apache221132 ?        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

此外,如果您想要 PID 列表,您也可以轻松地使用 grep 搜索:

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]*'

This approach is suitable for writing a simple empty string test, then even iterating through the discovered PIDs.

#!/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

警告!!!

请记住,您只是在解析 ps ax 的输出,这意味着,从 Linux 输出中可以看出,它不仅匹配进程,还匹配传递给那个程序。我强烈建议在使用此方法时尽可能具体(例如 ./running "mysql" 也将匹配 'mysqld' 进程)。我强烈建议尽可能使用 which 来检查完整路径。


引用资料:

http://linux.about.com/od/commands/l/blcmdl1_ps.htm

http://linux.about.com/od/commands/l/blcmdl1_grep.htm

关于Linux/Unix命令确定进程是否正在运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9117507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com