38

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?

Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
woodings
  • 7,503
  • 5
  • 34
  • 52
  • 2
    Could you make the same question but in [unix.se] site? – Braiam Jul 27 '13 at 05:51
  • Here is my solution which works for services too: http://pastebin.com/VjpVNdz2. – Antonio Petricca Mar 23 '16 at 16:49
  • 1
    Why is this "off topic"? It is a programming question relevant to the bash programming language. – Audrius Meškauskas Jan 20 '17 at 07:44
  • 1
    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? – guettli Jan 24 '18 at 08:55

2 Answers2

39

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:

ACV
  • 9,964
  • 5
  • 76
  • 81
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • 7
    Changed it to `while $(kill -0 $PID 2>/dev/null); do` to ignore the "No such proccess" message after the proccess was killed – Gus Aug 23 '18 at 13:25
  • 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 loop – Lou Jul 27 '22 at 13:12
  • 1
    If I'm not mistaken, `kill -0` does not actually kill the process, it simply checks whether the process is still running – Lou Jul 27 '22 at 13:15
2

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

 pkill <previous_pid>
 wait <previous_pid>
Roland Jansen
  • 2,733
  • 1
  • 16
  • 21