Kill a process and wait for the process to exit
31,564
Solution 1
No. What you can do is write a loop with kill -0 $PID
. If this call fails ($? -ne 0
), the process has terminated:
while kill -0 $PID; do
sleep 1
done
(kudos to qbolec for the code)
Related:
Solution 2
Use wait
(bash builtin) to wait for the process to finish:
pkill <previous_pid>
wait <previous_pid>
Author by
woodings
Updated on May 17, 2020Comments
-
woodings almost 4 years
When I start my tcp server from my bash script, I need to kill the previous instance (which may still be listening to the same port) right before the current instance starts listening.
I could use something like
pkill <previous_pid>
. If I understand it correctly, this just sendsSIGTERM
to the target pid. Whenpkill
returns, the target process may still be alive. Is there a way to letpkill
wait until it exits?