如何等待一个非子进程?

huangapple go评论48阅读模式
英文:

How to wait for a non-child process?

问题

当前我在执行:

```bash
while [ -d "/proc/$PID" ]; do
  sleep 1
done

由于它不是子进程,我无法使用 wait

问题在于 sleep 会阻塞任何信号陷阱处理程序(例如对于 SIGINT 或 SIGTERM),直到它不再休眠为止。因此,每个信号平均会延迟 0.5 秒。

我尝试使用 tail 代替等待 PID,但它也会阻塞陷阱处理程序(除非你从交互式 shell 中按下 CTRL-C)。我尝试使用 pwait / pidwait 但同样的问题:它们在接收到停止信号时不会退出。

那么,有没有一种好的方法来做到这一点,并仍然能够处理停止信号?


<details>
<summary>英文:</summary>

Currently I do:

    while [ -d &quot;/proc/$PID&quot;  ]; do
      sleep 1
    done

Since I cannot use `wait` as it is a non-child process.

The problem is that `sleep` blocks any signal trap handlers (for example for SIGINT or SIGTERM) until it is not sleeping anymore. So each signal will be delayed by 0.5 seconds on average.

I tried to use `tail` instead to wait for the PID, but it also blocks the trap handler (unless you press CTRL-C from interactive shell). I tried using `pwait` / `pidwait` but same problem: they don&#39;t exit when a stop signal is received.

So is there a good way to do this, and still be able to handle stop signals?


</details>


# 答案1
**得分**: 2

The solution was simple. Instead of calling `wait` on the PID, I need to call `wait` on the PID of an executable that is waiting for said PID. This allows the signal traps to be called while waiting.

For example:

    pidwait -F &quot;$PIDFILE&quot; &amp; wait $!

or:

    tail --pid &quot;$PID&quot; -f /dev/null &amp; wait $!

or even the original loop can be fixed this way by waiting on sleep:

    while [ -d &quot;/proc/$PID&quot;  ]; do
      sleep 1 &amp; wait $!
    done

This was a bit counter-intuitive, since you are waiting on something that is already waiting, but in hindsight it makes sense.

<details>
<summary>英文:</summary>

The solution was simple. Instead of calling `wait` on the PID, I need to call `wait` on the PID of an executable that is waiting for said PID. This allow the signal traps to be called while waiting.

For example:

    pidwait -F &quot;$PIDFILE&quot; &amp; wait $!

or:

    tail --pid &quot;$PID&quot; -f /dev/null &amp; wait $!

or even the original loop can be fixed this way by waiting on sleep:

    while [ -d &quot;/proc/$PID&quot;  ]; do
      sleep 1 &amp; wait $!
    done

This was a bit counter-intuitive, since you are waiting on something that is already waiting, but in hindsight it makes sense.

</details>



huangapple
  • 本文由 发表于 2023年4月16日 23:50:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76028781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定