Search code examples
bashprocesswaitpidsigterm

How to wait for a non-child process?


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?


Solution

  • 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.