Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill a process and wait for the process to exit

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 sends SIGTERM to the target pid. When pkill returns, the target process may still be alive. Is there a way to let pkill wait until it exits?

like image 901
woodings Avatar asked Jul 27 '13 05:07

woodings


2 Answers

No. What you can do is write a loop with kill -0 $PID. If this call fails ($? -ne 0), the process has terminated (after your normal kill):

while kill -0 $PID; do 
    sleep 1
done

(kudos to qbolec for the code)

Related:

  • What does `kill -0 $pid` in a shell script do?
like image 103
Aaron Digulla Avatar answered Sep 23 '22 16:09

Aaron Digulla


Use wait (bash builtin) to wait for the process to finish:

 pkill <previous_pid>
 wait <previous_pid>
like image 22
Roland Jansen Avatar answered Sep 23 '22 16:09

Roland Jansen