使用 ps 检查正在运行的脚本的数量
我正在编写一个脚本(show_volume.sh),该脚本可能会在短时间内被调用多次。我需要一种方法来确定该脚本是否有多个正在运行的实例。我想我可以使用ps
,所以我在Bash中编写了这个函数:
is_only_process(){
PCOUNT=`ps -a | grep show_volume.sh | wc -l`
echo $PCOUNT
if (( PCOUNT==1 )); then
return 1
fi
return 0
}
所以我添加了这两行
is_only_process
sleep 4
并启动了这个脚本一次,但是echo $PCOUNT
的输出没有对我来说有任何意义。我总是得到值 2,而不是预期的 1。当我运行此命令时
ps -a | grep show_volume.sh | | grep show_volume.sh | 当脚本运行时,我从另一个终端接收
到值 1。 当我连续运行这个脚本几次时,情况几乎是一样的,例如使用 for 循环运行 10 次。当我使用另一个终端时收到正确的值时,脚本本身会确定过高的值。
现在,为什么这个脚本要确定这些奇数值?
I'm writing a script (show_volume.sh) which may be called several times in short intervals. I need a way to determine whether there is more than just one running instance of this script. I figured I could use ps
, so I wrote this function in Bash:
is_only_process(){
PCOUNT=`ps -a | grep show_volume.sh | wc -l`
echo $PCOUNT
if (( PCOUNT==1 )); then
return 1
fi
return 0
}
So I added these 2 lines
is_only_process
sleep 4
and started this script once, but the output of echo $PCOUNT
does not make any sense to me. I always get the value 2, not 1, as expected. When I run this command
ps -a | grep show_volume.sh | wc -l
from another terminal while the script is running, I receive the value 1.
It's pretty much the same when I run this script several times in a row, e.g. 10 times using a for loop. The script itself determines values which are too high while I receive correct values when using another terminal.
Now, why does this script determine these odd values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
此时
ps
运行一个进程grep show_volume.sh
也在运行,所以你总是数grep!简单的解决方案,
grep s[h]ow_volume.sh
。 grep(不是 shell)会将[h]
折叠为h
并搜索你想要的内容,但是你的 grep 不会匹配自身,因为它会有 []参数。pgrep
对于此任务也很有用,并且足够聪明,可以始终排除自身。At the moment
ps
runs a processgrep show_volume.sh
is also running, so you always count the grep!Simple solution,
grep s[h]ow_volume.sh
. The grep (not shell) will collapse the[h]
toh
and search for what you want, but your grep won't match itself because it will have [] in the parameter.pgrep
is also useful for this task and is smart enough to always exclude itself.如果您以不同用户身份运行脚本,则
ps -a
将仅显示当前用户的实例,并且仅显示带有附加终端的实例。使用ps -ax
或ps -e
。将显示计数,而无需使用
wc
。If you're running the script as different users then
ps -a
will only show instances for the current user and only those with an attached terminal. Useps -ax
orps -e
.will show a count without having to use
wc
.尝试排除 grep 以及,因为你的 grep 本身也包含
show_volume.sh
,一个例子Try to exclude grep as well, as your grep itself also contains
show_volume.sh
, an exampleajreal提供的解决方案:
ps -a | grep show_volume.sh | | grep show_volume.sh | grep -v grep | grep -v wc -l
应该可以工作。如果没有,请提供
ps -a | 的输出grep show_volume.sh | | grep show_volume.sh | grep -v grep
在这里
The solution provided by ajreal:
ps -a | grep show_volume.sh | grep -v grep | wc -l
should work. If it does not, please provide output of
ps -a | grep show_volume.sh | grep -v grep
here