Kill a process and wait for the process to exit
Asked Answered
H

4

42

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?

Hanzelin answered 27/7, 2013 at 5:48 Comment(5)
Could you make the same question but in Unix & Linux site?Vicariate
Here is my solution which works for services too: pastebin.com/VjpVNdz2.Dentist
Why is this "off topic"? It is a programming question relevant to the bash programming language.Schaab
it's a pitty that fundamental needs are not solved up to now. I guess there are several thousand scripts which implement this simple feature: kill and wait until process has terminated. How to change the current situation? How to get to the goal?Edris
Relevant answer here: unix.stackexchange.com/a/427133Zurkow
L
41

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:

Letendre answered 26/3, 2015 at 14:56 Comment(3)
Changed it to while $(kill -0 $PID 2>/dev/null); do to ignore the "No such proccess" message after the proccess was killedOutskirts
I tried this, but it didn't kill the process, just looped infinitely. I think you need to actually run kill $PID within the while loopCallisthenics
If I'm not mistaken, kill -0 does not actually kill the process, it simply checks whether the process is still runningCallisthenics
F
3

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

 pkill <previous_pid>
 wait <previous_pid>
Foeticide answered 27/7, 2013 at 5:59 Comment(3)
wait said "is not a pid of this shell", I had to while ps -p $nPid; do sleep 1;done;Carrick
−1: wait only works for children of the current shell, not arbitrary processes. There is no general built-in mechanism for this.Pullen
why not use kill ?Rabblement
G
1

In my case it was easier to use the name of the process. It works like this:

pkill <process_name> && while pgrep -l <process_name>; do sleep 1;done;

Then, restart the process.

Grapheme answered 5/10, 2023 at 4:21 Comment(0)
M
0

Yes, you can do it with killall, e.g. killall --wait <process_name>. That polls every second, if you have the pid you can do it more efficiently with kill <pid> && pidwait <pid>.

Mandeville answered 27/6, 2024 at 16:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.