Bash – Listen for exit of process given pid $$

bashprocprocessshell-script

Say I have a pid in hand, mypid=$$

is there some bash/system command I can use to listen for the exit of that process with the given pid?

If no process with mypid exists, I guess the command should simply fail.

Best Answer

I got what I needed from this answer: https://stackoverflow.com/a/41613532/1223975

..turns out using wait <pid> will only work if that pid is a child process of the current process.

However the following will work for any process:

To wait for any process to finish

Linux:

tail --pid=$pid -f /dev/null

Darwin (requires that $pid has open files):

lsof -p $pid +r 1 &>/dev/null

With timeout (seconds)

Linux:

timeout $timeout tail --pid=$pid -f /dev/null

Darwin (requires that $pid has open files):

lsof -p $pid +r 1m%s -t | grep -qm1 $(date -v+${timeout}S +%s 2>/dev/null || echo INF)
Related Question