Linux bash:运行一个命令 n 分钟,然后 SIGHUP 它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4423934/
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-05 00:17:33  来源:igfitidea点击:

bash: run a command for n minutes, then SIGHUP it

linuxbashshelltimeout

提问by Paul A Jungwirth

Is there any bash/linux command to launch a long-running command, then kill it after n minutes? I guess I could hack something up with perl using fork and kill, but does anyone know of something already out there?

是否有任何 bash/linux 命令来启动长时间运行的命令,然后在 n 分钟后将其杀死?我想我可以使用 fork 和 kill 用 perl 破解一些东西,但是有人知道那里已经有什么东西了吗?

采纳答案by pixelbeat

See the timeoutcommand now in most GNU/Linux distros.

现在在大多数 GNU/Linux 发行版中查看timeout命令。

timeout -sHUP 10m command

The same functionality can be achieved with http://www.pixelbeat.org/scripts/timeout

使用http://www.pixelbeat.org/scripts/timeout可以实现相同的功能

回答by Marcus Borkenhagen

Try it with this one, it starts your command in the background, stores it's PID in $P, waits for some time and kills it with a SIGHUP.

试试这个,它在后台启动你的命令,将它的 PID 存储在 $P 中,等待一段时间并用SIGHUP.

yourCommand & PID=$!
sleep ${someMinutes}m
kill -HUP $PID

Cheers

干杯

PS: that assumes a sleep that knows about Nm (minutes), else, you might want to do some math :)

PS:假设睡眠知道 Nm(分钟),否则,您可能想做一些数学运算:)

回答by SiegeX

n=5
some_command &
pid=$!
at now + $n minutes <<<"kill -HUP $pid"

The benefit of using atover waiting for sleepis that your script wont block waiting for the sleep to expire. You can go and do other things and atwill asynchronously fire at the specified time. Depending on your script that may be a very important feature to have.

使用atover waiting for的好处sleep是您的脚本不会阻止等待睡眠到期。你可以去做其他事情,并且at会在指定的时间异步触发。根据您的脚本,这可能是一个非常重要的功能。