bash 使用 while 或直到等待 PID 不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11425876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:43:57  来源:igfitidea点击:

Using while or until to wait until a PID doesn't exist

bashprocess

提问by hexacyanide

I have been using Bash to wait until a PID no longer exists. I've tried

我一直在使用 Bash 等待 PID 不再存在。我试过了

#!/bin/bash
while [ kill -0 PID > /dev/null 2>&1 ]; do
    //code to kill process
done
//code to execute after process is dead

as well as

#!/bin/bash
until [ ! kill -0 PID > /dev/null 2>&1 ]; do
    //code to kill process
done
//code to execute after process is dead

Both these examples either fail to work, or keep on looping after the process has ended. What am I doing incorrectly?

这两个示例要么无法工作,要么在流程结束后继续循环。我做错了什么?

回答by Jonathan Leffler

You should be simply doing:

你应该简单地做:

while kill -0 $PID >/dev/null 2>&1
do
    # Code to kill process
done

The loop condition tests the exit status of the last command — in this case, kill. The -0option (used in the question) doesn't actually send any signal to the process, but it does check whether a signal could be sent — and it can't be sent if the process no longer exists. (See the POSIX specification of the kill()function and the POSIX killutility.)

循环条件测试最后一个命令的退出状态——在本例中为kill. 该-0选项(在问题中使用)实际上并未向进程发送任何信号,但它会检查是否可以发送信号——如果进程不再存在,则无法发送信号。(请参阅kill()函数的 POSIX 规范和 POSIXkill实用程序。)

The significance of 'last' is that you could write:

'last' 的意义在于你可以这样写:

while sleep 1
      echo Testing again
      kill -0 $PID >/dev/null 2>&1
do
    # Code to kill process
done

This too tests the exit status of kill(and killalone).

这也测试kill(和kill单独)的退出状态。

回答by Felipe Buccioni

Also you can do in unixes with procfs (almost all except mac os)

你也可以在 unixes 中使用 procfs(几乎所有除了 mac os)

while test -d /proc/$PID; do
     kill -$SIGNAL $PID
     # optionally
     sleep 0.2
done