I need a platform independent (Linux/Unix|OSX) shell/bash command that will determine if a specific process is running. e.g. mysqld
, httpd
... What is the simplest way/command to do this?
我需要一个平*立(Linux/Unix|OSX) shell/bash命令,它将决定一个特定的进程是否正在运行。例如mysqld,httpd……最简单的方法是什么?
13 个解决方案
#1
149
While pidof
and pgrep
are great tools for determining what's running, they are both, unfortunately, unavailable on some operating systems. A definite fail safe would be to use the following: ps cax | grep command
虽然pidof和pgrep是决定运行的重要工具,但不幸的是,它们都无法在某些操作系统上使用。一个确定的故障安全将是使用以下的:ps cax | grep命令。
The output on Gentoo Linux:
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:
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:
在Linux和OS X上,grep返回一个退出代码,因此很容易检查是否找到了这个过程:
#!/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:
此外,如果你想要的是PIDs的列表,你也可以很容易地为它们grep:
ps cax | grep httpd | grep -o '^[ ]*[0-9]*'
Whose output is the same on Linux and OS X:
其输出在Linux和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.
这种方法适合编写简单的空字符串测试,然后遍历发现的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
You can test it by saving it to a file (named "running") with execute permissions (chmod +x running) and executing it with a parameter: ./running "httpd"
您可以通过将其保存到一个名为“运行”的文件(名为“运行”)来测试它,并以一个参数来执行它:./运行“httpd”
#!/bin/bash
ps cax | grep httpd
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
WARNING!!!
警告! ! !
Please keep in mind that you're simply parsing the output of ps ax
which means that, as seen in the Linux output, it is not simply matching on processes, but also the arguments passed to that program. I highly recommend being as specific as possible when using this method (e.g. ./running "mysql"
will also match 'mysqld' processes). I highly recommend using which
to check against a full path where possible.
请记住,您只是在解析ps ax的输出,这意味着,正如在Linux输出中所看到的那样,它不仅仅是在进程上进行匹配,而且是传递给该程序的参数。我强烈建议在使用这个方法时尽可能的具体(例如,运行“mysql”也会匹配“mysqld”进程)。我强烈建议在可能的情况下使用它来检查完整的路径。
References:
引用:
http://linux.about.com/od/commands/l/blcmdl1_ps.htm
http://linux.about.com/od/commands/l/blcmdl1_ps.htm
http://linux.about.com/od/commands/l/blcmdl1_grep.htm
http://linux.about.com/od/commands/l/blcmdl1_grep.htm
#2
20
You SHOULD know the PID !
Finding a process by trying to do some kind of pattern recognition on the process arguments (like pgrep "mysqld"
) is a strategy that is doomed to fail sooner or later. What if you have two mysqld running? Forget that approach. You MAY get it right temporarily and it MAY work for a year or two but then something happens that you haven't thought about.
通过在过程参数(如pgrep“mysqld”)中尝试某种模式识别,找到一个过程是一种注定要迟早失败的策略。如果有两个mysqld运行怎么办?忘记的方法。你可能会暂时得到它,它可能会工作一两年,但之后会发生一些你没想过的事情。
Only the process id (pid) is truly unique.
只有进程id (pid)才是真正惟一的。
Always store the pid when you launch something in the background. In Bash this can be done with the $!
Bash variable. You will save yourself SO much trouble by doing so.
当您在后台启动某个东西时,总是存储pid。在Bash中,这可以用$!Bash变量。你这样做可以省去许多麻烦。
How to determine if process is running (by pid)
So now the question becomes how to know if a pid is running.
现在的问题是如何知道一个pid是否在运行。
Simply do:
只是做的事:
ps -o pid= -p <pid>
This is POSIX and hence portable. It will return the pid itself if the process is running or return nothing if the process is not running. Strictly speaking the command will return a single column, the pid
, but since we've given that an empty title header (the stuff immediately preceding the equals sign) and this is the only column requested then the ps command will not use header at all. Which is what we want because it makes parsing easier.
这是POSIX,因此是可移植的。如果进程正在运行,如果进程没有运行,它将返回pid本身。严格地说,命令将返回一个单独的列,pid,但是由于我们已经给出了一个空的标题头(即在等号前面的东西),而这是请求的唯一列,那么ps命令将不会使用header。这就是我们想要的,因为它使解析更容易。
This will work on Linux, BSD, Solaris, etc.
这将适用于Linux、BSD、Solaris等。
Another strategy would be to test on the exit value from the above ps
command. It should be zero if the process is running and non-zero if it isn't. The POSIX spec says that ps
must exit >0 if an error has occurred but it is unclear to me what constitutes 'an error'. Therefore I'm not personally using that strategy although I'm pretty sure it will work as well on all Unix/Linux platforms.
另一个策略是测试上面的ps命令的退出值。如果进程正在运行,它应该为零,如果不是,则为非零。POSIX规范指出,如果发生错误,ps必须退出>0,但我不清楚是什么构成了“错误”。因此,虽然我很肯定它在所有Unix/Linux平台上都能运行,但我并没有亲自使用该策略。
#3
12
On most Linux distributions, you can use pidof
(8).
在大多数Linux发行版中,您可以使用pidof(8)。
It will print the process ids of all running instances of specified processes, or nothing if there are no instances running.
它将打印指定进程的所有运行实例的进程id,如果没有实例运行,则没有任何内容。
For instance, on my system (I have four instances of bash
and one instance of remmina
running):
例如,在我的系统上(我有四个bashand实例,其中一个是remmina正在运行的实例):
$ pidof bash remmina
6148 6147 6144 5603 21598
On other Unices, pgrep
or a combination of ps
and grep
will achieve the same thing, as others have rightfully pointed out.
对于其他的Unices, pgrep或者ps和grep的组合将会达到同样的效果,正如其他人已经正确指出的那样。
#4
6
The simpliest way is to use ps and grep:
最简单的方法是使用ps和grep:
command="httpd"
running=`ps ax | grep -v grep | grep $command | wc -l`
if [ running -gt 0 ]; then
echo "Command is running"
else
echo "Command is not running"
fi
If your command has some command arguments, then you can also put more 'grep cmd_arg1' after 'grep $command' to filter out other possible processes that you are not interested in.
如果您的命令有一些命令参数,那么您还可以在“grep $command”之后添加更多的“grep cmd_arg1”,以过滤掉您不感兴趣的其他可能进程。
Example: show me if any java process with supplied argument:
示例:如果有任何java进程提供了参数:
-Djava.util.logging.config.file=logging.properties
-Djava.util.logging.config.file = logging.properties
is running
正在运行
ps ax | grep -v grep | grep java | grep java.util.logging.config.file=logging.properties | wc -l
#5
6
This should work on most flavours of Unix, BSD and Linux:
这应该适用于Unix、BSD和Linux的大多数风格:
PATH=/usr/ucb:${PATH} ps aux | grep httpd | grep -v grep
Tested on:
测试:
- SunOS 5.10 [Hence the
PATH=...
] - SunOS 5.10[因此路径=…]
- Linux 2.6.32 (CentOS)
- Linux 2.6.32(CentOS)
- Linux 3.0.0 (Ubuntu)
- Ubuntu Linux 3.0.0()
- Darwin 11.2.0
- 达尔文11.2.0
- FreeBSD 9.0-STABLE
- FreeBSD 9.0稳定
- Red Hat Enterprise Linux ES release 4
- Red Hat Enterprise Linux ES release 4。
- Red Hat Enterprise Linux Server release 5
- 红帽企业Linux服务器版本5。
#6
5
Just a minor addition: if you add the -c
flag to ps, you don't need to remove the line containing the grep process with grep -v
afterwards. I.e.
只是一个小的添加:如果将-c标志添加到ps中,就不需要删除包含grep -v的grep进程的行。即。
ps acux | grep cron
is all the typing you'll need on a bsd-ish system (this includes MacOSX) You can leave the -u
away if you need less information.
在bsd-ish系统(包括MacOSX)中,您需要的所有类型的输入都可以离开-u,如果您需要的信息更少的话。
On a system where the genetics of the native ps
command point back to SysV, you'd use
在一个系统中,本机ps命令指向SysV,您将使用。
ps -e |grep cron
or
或
ps -el |grep cron
for a listing containing more than just pid and process name. Of course you could select the specific fields to print out using the -o <field,field,...>
option.
对于包含不只是pid和进程名称的列表。当然,您可以选择使用-o
#7
4
Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:
把各种各样的建议放在一起,我能想出的最干净的版本(没有不可靠的grep,触发了部分单词)是:
kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:
kill -0不会杀死进程,但是检查它是否存在,然后返回true,如果您的系统中没有pidof,则在启动进程时存储pid:
$ mysql &
$ echo $! > pid_stored
then in the script:
然后在脚本:
kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
#8
3
I use pgrep -l httpd
but not sure it is present on any platform...
Who can confirm on OSX?
我使用pgrep -l httpd,但不确定它是否存在于任何平台上……谁能证实OSX?
#9
1
You should know the PID of your process.
When you launch it, its PID will be recorded in the $!
variable. Save this PID into a file.
当你启动它,它的PID将被记录在$!变量。将此PID保存到文件中。
Then you will need to check if this PID corresponds to a running process. Here's a complete skeleton script:
然后您需要检查这个PID是否对应于一个正在运行的进程。这里有一个完整的框架脚本:
FILE="/tmp/myapp.pid"
if [ -f $FILE ];
then
PID=$(cat $FILE)
else
PID=1
fi
ps -o pid= -p $PID
if [ $? -eq 0 ]; then
echo "Process already running."
else
echo "Starting process."
run_my_app &
echo $! > $FILE
fi
Based on the answer of peterh
. The trick for knowing if a given PID is running is in the ps -o pid= -p $PID
instruction.
基于peterh的答案。知道一个给定的PID是否正在运行的技巧是在ps -o PID = -p $PID指令中。
#10
0
This approach can be used in case commands 'ps', 'pidof' and rest are not available. I personally use procfs very frequently in my tools/scripts/programs.
这种方法可以用于case命令'ps', 'pidof'和rest是不可用的。我经常在我的工具/脚本/程序中使用procfs。
egrep -m1 "mysqld$|httpd$" /proc/[0-9]*/status | cut -d'/' -f3
Little explanation what is going on:
很少解释发生了什么:
- -m1 - stop process on first match
- -m1 -在第一场比赛停止。
- "mysqld$|httpd$" - grep will match lines which ended on mysqld OR httpd
- “mysqld$|httpd$”- grep将匹配以mysqld或httpd结束的行。
- /proc/[0-9]* - bash will match line which started with any number
- /proc/[0-9]* - bash将匹配以任何数字开头的行。
- cut - just split the output by delimiter '/' and extract field 3
- cut - just split the output by delimiter '/' and extract field 3。
#11
0
This prints the number of processes whose basename is "chromium-browser":
这将打印basename为“chromium-browser”的进程的数量:
ps -e -o args= | awk 'BEGIN{c=0}{
if(!match($1,/^\[.*\]$/)){sub(".*/","",$1)} # Do not strip process names enclosed by square brackets.
if($1==cmd){c++}
}END{print c}' cmd="chromium-browser"
If this prints "0", the process is not running. The command assumes process path does not contain breaking space. I have not tested this with suspended processes or zombie processes.
如果此输出为“0”,则进程没有运行。命令假设过程路径不包含中断空间。我还没有通过暂停进程或僵尸进程来测试这个。
Tested using gwak
as the awk
alternative in Linux.
在Linux中测试使用gwak作为awk替代。
Here is a more versatile solution with some example usage:
这里有一个更通用的解决方案,有一些示例用法:
#!/bin/sh
isProcessRunning() {
if [ "${1-}" = "-q" ]; then
local quiet=1;
shift
else
local quiet=0;
fi
ps -e -o pid,args= | awk 'BEGIN{status=1}{
name=$2
if(name !~ /^\[.*\]$/){sub(".*/","",name)} # strip dirname, if process name is not enclosed by square brackets.
if(name==cmd){status=0; if(q){exit}else{print $0}}
}END{exit status}' cmd="$1" q=$quiet
}
process='chromium-browser'
printf "Process \"${process}\" is "
if isProcessRunning -q "$process"
then printf "running.\n"
else printf "not running.\n"; fi
printf "Listing of matching processes (PID and process name with command line arguments):\n"
isProcessRunning "$process"
#12
0
Here is my version. Features:
这是我的版本。特点:
- checks for exact program name (first argument of the function). search for "mysql" will not match running "mysqld"
- 检查准确的程序名称(函数的第一个参数)。搜索“mysql”将不匹配运行“mysqld”
- searches program arguments (second argument of the function)
- 搜索程序参数(函数的第二个参数)
script:
脚本:
#!/bin/bash
# $1 - cmd
# $2 - args
# return: 0 - no error, running; 1 - error, not running
function isRunning() {
for i in $(pidof $1); do
cat /proc/$i/cmdline | tr '\000' ' ' | grep -F -e "$2" 1>&2> /dev/null
if [ $? -eq 0 ]; then
return 0
fi
done
return 1
}
isRunning java "-Djava.util.logging.config.file=logging.properties"
if [ $? -ne 0 ]; then
echo "not running, starting..."
fi
#13
-1
The following shell function, being only based on POSIX standard commands and options should work on most (if not any) Unix and linux system. :
下面的shell函数,只基于POSIX标准命令和选项,应该在大多数(如果不是任何)Unix和linux系统上工作。:
isPidRunning() {
cmd=`
PATH=\`getconf PATH\` export PATH
ps -e -o pid= -o comm= |
awk '$2 ~ "^.*/'"$1"'$" || $2 ~ "^'"$1"'$" {print $1,$2}'
`
[ -n "$cmd" ] &&
printf "%s is running\n%s\n\n" "$1" "$cmd" ||
printf "%s is not running\n\n" $1
[ -n "$cmd" ]
}
$ isPidRunning httpd
httpd is running
586 /usr/apache/bin/httpd
588 /usr/apache/bin/httpd
$ isPidRunning ksh
ksh is running
5230 ksh
$ isPidRunning bash
bash is not running
Note that it will choke when passed the dubious "0]" command name and will also fail to identify processes having an embedded space in their names.
请注意,当传递可疑的“0”命令名时,它将会阻塞,并且将无法识别在其名称中包含嵌入空间的进程。
Note too that the most upvoted and accepted solution demands non portable ps
options and gratuitously uses a shell that is, despite its popularity, not guaranteed to be present on every Unix/Linux machine (bash
)
请注意,最向上的和被接受的解决方案要求不可移植的ps选项,并且免费使用一个shell,尽管它很受欢迎,但不保证在每个Unix/Linux机器上都存在(bash)
#1
149
While pidof
and pgrep
are great tools for determining what's running, they are both, unfortunately, unavailable on some operating systems. A definite fail safe would be to use the following: ps cax | grep command
虽然pidof和pgrep是决定运行的重要工具,但不幸的是,它们都无法在某些操作系统上使用。一个确定的故障安全将是使用以下的:ps cax | grep命令。
The output on Gentoo Linux:
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:
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:
在Linux和OS X上,grep返回一个退出代码,因此很容易检查是否找到了这个过程:
#!/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:
此外,如果你想要的是PIDs的列表,你也可以很容易地为它们grep:
ps cax | grep httpd | grep -o '^[ ]*[0-9]*'
Whose output is the same on Linux and OS X:
其输出在Linux和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.
这种方法适合编写简单的空字符串测试,然后遍历发现的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
You can test it by saving it to a file (named "running") with execute permissions (chmod +x running) and executing it with a parameter: ./running "httpd"
您可以通过将其保存到一个名为“运行”的文件(名为“运行”)来测试它,并以一个参数来执行它:./运行“httpd”
#!/bin/bash
ps cax | grep httpd
if [ $? -eq 0 ]; then
echo "Process is running."
else
echo "Process is not running."
fi
WARNING!!!
警告! ! !
Please keep in mind that you're simply parsing the output of ps ax
which means that, as seen in the Linux output, it is not simply matching on processes, but also the arguments passed to that program. I highly recommend being as specific as possible when using this method (e.g. ./running "mysql"
will also match 'mysqld' processes). I highly recommend using which
to check against a full path where possible.
请记住,您只是在解析ps ax的输出,这意味着,正如在Linux输出中所看到的那样,它不仅仅是在进程上进行匹配,而且是传递给该程序的参数。我强烈建议在使用这个方法时尽可能的具体(例如,运行“mysql”也会匹配“mysqld”进程)。我强烈建议在可能的情况下使用它来检查完整的路径。
References:
引用:
http://linux.about.com/od/commands/l/blcmdl1_ps.htm
http://linux.about.com/od/commands/l/blcmdl1_ps.htm
http://linux.about.com/od/commands/l/blcmdl1_grep.htm
http://linux.about.com/od/commands/l/blcmdl1_grep.htm
#2
20
You SHOULD know the PID !
Finding a process by trying to do some kind of pattern recognition on the process arguments (like pgrep "mysqld"
) is a strategy that is doomed to fail sooner or later. What if you have two mysqld running? Forget that approach. You MAY get it right temporarily and it MAY work for a year or two but then something happens that you haven't thought about.
通过在过程参数(如pgrep“mysqld”)中尝试某种模式识别,找到一个过程是一种注定要迟早失败的策略。如果有两个mysqld运行怎么办?忘记的方法。你可能会暂时得到它,它可能会工作一两年,但之后会发生一些你没想过的事情。
Only the process id (pid) is truly unique.
只有进程id (pid)才是真正惟一的。
Always store the pid when you launch something in the background. In Bash this can be done with the $!
Bash variable. You will save yourself SO much trouble by doing so.
当您在后台启动某个东西时,总是存储pid。在Bash中,这可以用$!Bash变量。你这样做可以省去许多麻烦。
How to determine if process is running (by pid)
So now the question becomes how to know if a pid is running.
现在的问题是如何知道一个pid是否在运行。
Simply do:
只是做的事:
ps -o pid= -p <pid>
This is POSIX and hence portable. It will return the pid itself if the process is running or return nothing if the process is not running. Strictly speaking the command will return a single column, the pid
, but since we've given that an empty title header (the stuff immediately preceding the equals sign) and this is the only column requested then the ps command will not use header at all. Which is what we want because it makes parsing easier.
这是POSIX,因此是可移植的。如果进程正在运行,如果进程没有运行,它将返回pid本身。严格地说,命令将返回一个单独的列,pid,但是由于我们已经给出了一个空的标题头(即在等号前面的东西),而这是请求的唯一列,那么ps命令将不会使用header。这就是我们想要的,因为它使解析更容易。
This will work on Linux, BSD, Solaris, etc.
这将适用于Linux、BSD、Solaris等。
Another strategy would be to test on the exit value from the above ps
command. It should be zero if the process is running and non-zero if it isn't. The POSIX spec says that ps
must exit >0 if an error has occurred but it is unclear to me what constitutes 'an error'. Therefore I'm not personally using that strategy although I'm pretty sure it will work as well on all Unix/Linux platforms.
另一个策略是测试上面的ps命令的退出值。如果进程正在运行,它应该为零,如果不是,则为非零。POSIX规范指出,如果发生错误,ps必须退出>0,但我不清楚是什么构成了“错误”。因此,虽然我很肯定它在所有Unix/Linux平台上都能运行,但我并没有亲自使用该策略。
#3
12
On most Linux distributions, you can use pidof
(8).
在大多数Linux发行版中,您可以使用pidof(8)。
It will print the process ids of all running instances of specified processes, or nothing if there are no instances running.
它将打印指定进程的所有运行实例的进程id,如果没有实例运行,则没有任何内容。
For instance, on my system (I have four instances of bash
and one instance of remmina
running):
例如,在我的系统上(我有四个bashand实例,其中一个是remmina正在运行的实例):
$ pidof bash remmina
6148 6147 6144 5603 21598
On other Unices, pgrep
or a combination of ps
and grep
will achieve the same thing, as others have rightfully pointed out.
对于其他的Unices, pgrep或者ps和grep的组合将会达到同样的效果,正如其他人已经正确指出的那样。
#4
6
The simpliest way is to use ps and grep:
最简单的方法是使用ps和grep:
command="httpd"
running=`ps ax | grep -v grep | grep $command | wc -l`
if [ running -gt 0 ]; then
echo "Command is running"
else
echo "Command is not running"
fi
If your command has some command arguments, then you can also put more 'grep cmd_arg1' after 'grep $command' to filter out other possible processes that you are not interested in.
如果您的命令有一些命令参数,那么您还可以在“grep $command”之后添加更多的“grep cmd_arg1”,以过滤掉您不感兴趣的其他可能进程。
Example: show me if any java process with supplied argument:
示例:如果有任何java进程提供了参数:
-Djava.util.logging.config.file=logging.properties
-Djava.util.logging.config.file = logging.properties
is running
正在运行
ps ax | grep -v grep | grep java | grep java.util.logging.config.file=logging.properties | wc -l
#5
6
This should work on most flavours of Unix, BSD and Linux:
这应该适用于Unix、BSD和Linux的大多数风格:
PATH=/usr/ucb:${PATH} ps aux | grep httpd | grep -v grep
Tested on:
测试:
- SunOS 5.10 [Hence the
PATH=...
] - SunOS 5.10[因此路径=…]
- Linux 2.6.32 (CentOS)
- Linux 2.6.32(CentOS)
- Linux 3.0.0 (Ubuntu)
- Ubuntu Linux 3.0.0()
- Darwin 11.2.0
- 达尔文11.2.0
- FreeBSD 9.0-STABLE
- FreeBSD 9.0稳定
- Red Hat Enterprise Linux ES release 4
- Red Hat Enterprise Linux ES release 4。
- Red Hat Enterprise Linux Server release 5
- 红帽企业Linux服务器版本5。
#6
5
Just a minor addition: if you add the -c
flag to ps, you don't need to remove the line containing the grep process with grep -v
afterwards. I.e.
只是一个小的添加:如果将-c标志添加到ps中,就不需要删除包含grep -v的grep进程的行。即。
ps acux | grep cron
is all the typing you'll need on a bsd-ish system (this includes MacOSX) You can leave the -u
away if you need less information.
在bsd-ish系统(包括MacOSX)中,您需要的所有类型的输入都可以离开-u,如果您需要的信息更少的话。
On a system where the genetics of the native ps
command point back to SysV, you'd use
在一个系统中,本机ps命令指向SysV,您将使用。
ps -e |grep cron
or
或
ps -el |grep cron
for a listing containing more than just pid and process name. Of course you could select the specific fields to print out using the -o <field,field,...>
option.
对于包含不只是pid和进程名称的列表。当然,您可以选择使用-o
#7
4
Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:
把各种各样的建议放在一起,我能想出的最干净的版本(没有不可靠的grep,触发了部分单词)是:
kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:
kill -0不会杀死进程,但是检查它是否存在,然后返回true,如果您的系统中没有pidof,则在启动进程时存储pid:
$ mysql &
$ echo $! > pid_stored
then in the script:
然后在脚本:
kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
#8
3
I use pgrep -l httpd
but not sure it is present on any platform...
Who can confirm on OSX?
我使用pgrep -l httpd,但不确定它是否存在于任何平台上……谁能证实OSX?
#9
1
You should know the PID of your process.
When you launch it, its PID will be recorded in the $!
variable. Save this PID into a file.
当你启动它,它的PID将被记录在$!变量。将此PID保存到文件中。
Then you will need to check if this PID corresponds to a running process. Here's a complete skeleton script:
然后您需要检查这个PID是否对应于一个正在运行的进程。这里有一个完整的框架脚本:
FILE="/tmp/myapp.pid"
if [ -f $FILE ];
then
PID=$(cat $FILE)
else
PID=1
fi
ps -o pid= -p $PID
if [ $? -eq 0 ]; then
echo "Process already running."
else
echo "Starting process."
run_my_app &
echo $! > $FILE
fi
Based on the answer of peterh
. The trick for knowing if a given PID is running is in the ps -o pid= -p $PID
instruction.
基于peterh的答案。知道一个给定的PID是否正在运行的技巧是在ps -o PID = -p $PID指令中。
#10
0
This approach can be used in case commands 'ps', 'pidof' and rest are not available. I personally use procfs very frequently in my tools/scripts/programs.
这种方法可以用于case命令'ps', 'pidof'和rest是不可用的。我经常在我的工具/脚本/程序中使用procfs。
egrep -m1 "mysqld$|httpd$" /proc/[0-9]*/status | cut -d'/' -f3
Little explanation what is going on:
很少解释发生了什么:
- -m1 - stop process on first match
- -m1 -在第一场比赛停止。
- "mysqld$|httpd$" - grep will match lines which ended on mysqld OR httpd
- “mysqld$|httpd$”- grep将匹配以mysqld或httpd结束的行。
- /proc/[0-9]* - bash will match line which started with any number
- /proc/[0-9]* - bash将匹配以任何数字开头的行。
- cut - just split the output by delimiter '/' and extract field 3
- cut - just split the output by delimiter '/' and extract field 3。
#11
0
This prints the number of processes whose basename is "chromium-browser":
这将打印basename为“chromium-browser”的进程的数量:
ps -e -o args= | awk 'BEGIN{c=0}{
if(!match($1,/^\[.*\]$/)){sub(".*/","",$1)} # Do not strip process names enclosed by square brackets.
if($1==cmd){c++}
}END{print c}' cmd="chromium-browser"
If this prints "0", the process is not running. The command assumes process path does not contain breaking space. I have not tested this with suspended processes or zombie processes.
如果此输出为“0”,则进程没有运行。命令假设过程路径不包含中断空间。我还没有通过暂停进程或僵尸进程来测试这个。
Tested using gwak
as the awk
alternative in Linux.
在Linux中测试使用gwak作为awk替代。
Here is a more versatile solution with some example usage:
这里有一个更通用的解决方案,有一些示例用法:
#!/bin/sh
isProcessRunning() {
if [ "${1-}" = "-q" ]; then
local quiet=1;
shift
else
local quiet=0;
fi
ps -e -o pid,args= | awk 'BEGIN{status=1}{
name=$2
if(name !~ /^\[.*\]$/){sub(".*/","",name)} # strip dirname, if process name is not enclosed by square brackets.
if(name==cmd){status=0; if(q){exit}else{print $0}}
}END{exit status}' cmd="$1" q=$quiet
}
process='chromium-browser'
printf "Process \"${process}\" is "
if isProcessRunning -q "$process"
then printf "running.\n"
else printf "not running.\n"; fi
printf "Listing of matching processes (PID and process name with command line arguments):\n"
isProcessRunning "$process"
#12
0
Here is my version. Features:
这是我的版本。特点:
- checks for exact program name (first argument of the function). search for "mysql" will not match running "mysqld"
- 检查准确的程序名称(函数的第一个参数)。搜索“mysql”将不匹配运行“mysqld”
- searches program arguments (second argument of the function)
- 搜索程序参数(函数的第二个参数)
script:
脚本:
#!/bin/bash
# $1 - cmd
# $2 - args
# return: 0 - no error, running; 1 - error, not running
function isRunning() {
for i in $(pidof $1); do
cat /proc/$i/cmdline | tr '\000' ' ' | grep -F -e "$2" 1>&2> /dev/null
if [ $? -eq 0 ]; then
return 0
fi
done
return 1
}
isRunning java "-Djava.util.logging.config.file=logging.properties"
if [ $? -ne 0 ]; then
echo "not running, starting..."
fi
#13
-1
The following shell function, being only based on POSIX standard commands and options should work on most (if not any) Unix and linux system. :
下面的shell函数,只基于POSIX标准命令和选项,应该在大多数(如果不是任何)Unix和linux系统上工作。:
isPidRunning() {
cmd=`
PATH=\`getconf PATH\` export PATH
ps -e -o pid= -o comm= |
awk '$2 ~ "^.*/'"$1"'$" || $2 ~ "^'"$1"'$" {print $1,$2}'
`
[ -n "$cmd" ] &&
printf "%s is running\n%s\n\n" "$1" "$cmd" ||
printf "%s is not running\n\n" $1
[ -n "$cmd" ]
}
$ isPidRunning httpd
httpd is running
586 /usr/apache/bin/httpd
588 /usr/apache/bin/httpd
$ isPidRunning ksh
ksh is running
5230 ksh
$ isPidRunning bash
bash is not running
Note that it will choke when passed the dubious "0]" command name and will also fail to identify processes having an embedded space in their names.
请注意,当传递可疑的“0”命令名时,它将会阻塞,并且将无法识别在其名称中包含嵌入空间的进程。
Note too that the most upvoted and accepted solution demands non portable ps
options and gratuitously uses a shell that is, despite its popularity, not guaranteed to be present on every Unix/Linux machine (bash
)
请注意,最向上的和被接受的解决方案要求不可移植的ps选项,并且免费使用一个shell,尽管它很受欢迎,但不保证在每个Unix/Linux机器上都存在(bash)