英文:
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 "/proc/$PID" ]; 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'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 "$PIDFILE" & wait $!
or:
tail --pid "$PID" -f /dev/null & wait $!
or even the original loop can be fixed this way by waiting on sleep:
while [ -d "/proc/$PID" ]; do
sleep 1 & 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 "$PIDFILE" & wait $!
or:
tail --pid "$PID" -f /dev/null & wait $!
or even the original loop can be fixed this way by waiting on sleep:
while [ -d "/proc/$PID" ]; do
sleep 1 & 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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论