Sometimes, I realize I need to run another command when a process completes. If it's in the same shell (and I can control-Z it), then Can I somehow add a "&& prog2" to an already running prog1? provides many good solutions. However, those only work if it's a child process.
There is the fairly standard idiom, at least for processes sharing the same user-id, which looks like this in shell:
while kill -s 0 $pid 2> /dev/null; do sleep 1; done
On systems with /proc
(like Linux), you can use [ -d /proc/$pid ]
instead of kill
to dispense of the same user-id requirement.
But both of those have a race condition: the process could exit during the sleep
and then a new process could obtain the same PID. The loop would thus continue, unaware the process it was interested in actually exited.
Is there a way to eliminate the race condition in a shell script?
cd /proc/$pid && ...
to avoid yet another race condition should$pid
exit before thecd
gets run – thrig Jun 02 '17 at 20:27cd
runs the cd fails, the error is improperly unchecked for, and the while loop loops forever in whatever directory that subshell started out in. – thrig Jun 03 '17 at 14:27cd
. – derobert Jun 03 '17 at 18:17