如何等待一个非子进程?

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

How to wait for a non-child process?

问题

  1. 当前我在执行:
  2. ```bash
  3. while [ -d "/proc/$PID" ]; do
  4. sleep 1
  5. done

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

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

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

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

  1. <details>
  2. <summary>英文:</summary>
  3. Currently I do:
  4. while [ -d &quot;/proc/$PID&quot; ]; do
  5. sleep 1
  6. done
  7. Since I cannot use `wait` as it is a non-child process.
  8. 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.
  9. 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.
  10. So is there a good way to do this, and still be able to handle stop signals?
  11. </details>
  12. # 答案1
  13. **得分**: 2
  14. 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.
  15. For example:
  16. pidwait -F &quot;$PIDFILE&quot; &amp; wait $!
  17. or:
  18. tail --pid &quot;$PID&quot; -f /dev/null &amp; wait $!
  19. or even the original loop can be fixed this way by waiting on sleep:
  20. while [ -d &quot;/proc/$PID&quot; ]; do
  21. sleep 1 &amp; wait $!
  22. done
  23. This was a bit counter-intuitive, since you are waiting on something that is already waiting, but in hindsight it makes sense.
  24. <details>
  25. <summary>英文:</summary>
  26. 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.
  27. For example:
  28. pidwait -F &quot;$PIDFILE&quot; &amp; wait $!
  29. or:
  30. tail --pid &quot;$PID&quot; -f /dev/null &amp; wait $!
  31. or even the original loop can be fixed this way by waiting on sleep:
  32. while [ -d &quot;/proc/$PID&quot; ]; do
  33. sleep 1 &amp; wait $!
  34. done
  35. This was a bit counter-intuitive, since you are waiting on something that is already waiting, but in hindsight it makes sense.
  36. </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:

确定