Linux 简短的简单命令如何向进程发送 SIGTERM 并在 X 秒内不存在时发送 SIGKILL?
应该如何查看 Linux 命令向进程/PID 发送终止信号,如果它在 10 秒后未能正常退出,则将其杀死?
我的尝试是:“sudo timeout -vk 5 10 Kill PIDhere”(-v verbose,-k Kill after X秒),但我不确定它是否好或如何调整值,或者是否有更好的命令可以使用进程命令行中显示的名称的一部分。 (“ps aux”输出)
How should look the Linux command to send terminate signal to the process/PID and if it fails to exit gracefully after 10 seconds kill it?
My attempt is: "sudo timeout -vk 5 10 kill PIDhere" (-v verbose, -k kill after X seconds) but I am not sure if it is good or how to adjust values or if there is better command that even work with part of the name shown in process COMMAND line. ("ps aux" output)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将执行
kill
,然后尝试终止该进程(如果需要太长时间)。这不应该发生,并且可能不是您想要的(如果kill
实际上挂起,杀死它不会影响您的实际进程)。timeout
对于限制进程运行的时间很有用,而不是收到信号后需要多长时间才能终止。相反,我建议异步启动进程(例如在 shell 中使用
&
,但任何语言的子进程库都将具有类似的功能),然后在向进程发送信号后等待进程终止。我在这个答案中描述了用Java执行此操作。在 shell 中可能如下所示:或者您可以依赖
wait
,如果作业在sleep
完成之前终止,它将提前返回:您可以使用 PID 执行与上面相同的操作它不是作业 ID,只是稍微复杂一点,因为您必须担心 PID 重用。
pkill
做你想做的事?Will execute
kill
, and then attempt to terminate that process if it takes too long. Which shouldn't happen, and presumably isn't what you want (ifkill
was actually hanging, killing it would not affect your actual process).timeout
is useful for capping how long a process runs for, not how long it takes to terminate after receiving a signal.Instead, I'd suggest starting the process asynchronously (e.g. using
&
in a shell, but any language's subprocess library will have similar functionality) and then waiting for the process to terminate after you send it a signal. I describe doing this in Java in this answer. In the shell that might look like:Or you could rely on
wait
which will return early if the job terminates before thesleep
completes:You can do the same as above with PIDs instead of job IDs, it's just a little more fiddly because you have to worry about PID reuse.
Does
pkill
do what you want?