简体   繁体   English

终止进程并等待进程退出

[英]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. 当我从我的bash脚本启动我的tcp服务器时,我需要在当前实例开始侦听之前杀死前一个实例(可能仍在侦听同一个端口)。

I could use something like pkill <previous_pid> . 我可以使用像pkill <previous_pid>这样的东西。 If I understand it correctly, this just sends SIGTERM to the target pid. 如果我理解正确,这只会将SIGTERM发送到目标pid。 When pkill returns, the target process may still be alive. pkill返回时,目标进程可能仍然存在。 Is there a way to let pkill wait until it exits? 有没有办法让pkill等到它退出?

No. What you can do is write a loop with kill -0 $PID . 不。你可以做的是用kill -0 $PID写一个循环。 If this call fails ( $? -ne 0 ), the process has terminated: 如果此调用失败( $? -ne 0 ),则该进程已终止:

while kill -0 $PID; do 
    sleep 1
done

(kudos to qbolec for the code) (对qbolec的代码赞不绝口

Related: 有关:

Use wait (bash builtin) to wait for the process to finish: 使用wait (bash builtin)等待进程完成:

 pkill <previous_pid>
 wait <previous_pid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM