Linux 杀死进程并等待进程退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17894720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:23:13  来源:igfitidea点击:

Kill a process and wait for the process to exit

linuxbashunixprocesskill-process

提问by woodings

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>. If I understand it correctly, this just sends SIGTERMto the target pid. When pkillreturns, the target process may still be alive. Is there a way to let pkillwait until it exits?

我可以使用类似的东西pkill <previous_pid>。如果我理解正确,这只会发送SIGTERM到目标 pid。当pkill返回时,目标进程可能仍然活着。有没有办法让它pkill等到它退出?

回答by Roland Jansen

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

使用wait(bash builtin) 等待进程完成:

 pkill <previous_pid>
 wait <previous_pid>

回答by Aaron Digulla

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

不。你可以做的是用kill -0 $PID. 如果此调用失败 ( $? -ne 0),则进程已终止:

while kill -0 $PID; do 
    sleep 1
done

(kudos to qbolecfor the code)

感谢 qbolec的代码)

Related:

有关的: