【问题标题】:Using while or until to wait until a PID doesn't exist使用 while 或 until 等到 PID 不存在
【发布时间】:2012-07-10 16:06:15
【问题描述】:

我一直在使用 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

还有

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

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

【问题讨论】:

  • 你不能只用wait "$PID"吗?
  • 它将返回 PID 不是 shell 的子代。
  • 除非您所观察的进程是子进程,否则会有几个陷阱。详情请见this comment

标签: bash process


【解决方案1】:

你应该只是在做:

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

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

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我没有注意到mac没有procfs。
    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 2022-08-19
    • 1970-01-01
    • 2012-01-07
    • 2018-03-16
    • 2016-03-09
    • 2020-07-17
    • 1970-01-01
    相关资源
    最近更新 更多