简体   繁体   English

Linux 简短命令如何将 SIGTERM 发送到进程,如果它在 X 秒内不存在则发送 SIGKILL?

[英]Linux short simple command how to send SIGTERM to a process and SIGKILL if it fails to exist in X seconds?

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?应该如何看待 Linux 命令向进程/PID 发送终止信号,如果它在 10 秒后无法正常退出,则终止它?

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.我的尝试是:“sudo timeout -vk 5 10 kill PIDhere”(-v verbose,-k kill after X seconds)但我不确定它是否好或如何调整值或者是否有更好的命令甚至可以使用进程命令行中显示的名称的一部分。 ("ps aux" output) (“ps aux”输出)

sudo timeout -vk 5 10 kill PIDhere

Will execute kill , and then attempt to terminate that process if it takes too long.将执行kill ,然后在花费太长时间时尝试终止进程。 Which shouldn't happen, and presumably isn't what you want (if kill was actually hanging, killing it would not affect your actual process).这不应该发生,而且可能不是你想要的(如果kill实际上挂了,杀死它不会影响你的实际过程)。 timeout is useful for capping how long a process runs for, not how long it takes to terminate after receiving a signal. timeout对于限制进程运行多长时间很有用,而不是在收到信号后终止需要多长时间。

Instead, I'd suggest starting the process asynchronously (eg 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.相反,我建议异步启动进程(例如,在 shell 中使用& ,但任何语言的子进程库都将具有类似的功能),然后在向进程发送信号后等待进程终止。 I describe doing this in Java in this answer .我在这个答案的 Java 中描述了这样做。 In the shell that might look like:在 shell 中可能如下所示:

$ some_process &
# time passes, eventually we decide to terminate the process
$ kill %1
$ sleep 5s
$ kill -s SIGKILL %1 # will fail and do nothing if %1 has already finished

Or you could rely on wait which will return early if the job terminates before the sleep completes:或者你可以依赖wait ,如果作业在sleep完成之前终止,它会提前返回:

$ some_process &
# time passes
$ kill %1
$ sleep 5s &
$ wait -n %1 %2       # returns once %1 or %2 (sleep) complete
$ kill -s SIGKILL %1  # if %2 completes first %1 is still running and will be killed

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.您可以使用 PID 而不是作业 ID 执行与上述相同的操作,这只是有点麻烦,因为您必须担心 PID 重用。

if there is better command that even work with part of the name如果有更好的命令甚至可以使用部分名称

Does pkill do what you want? pkill做你想做的事吗?

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

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