如何在一段时间内无输出地杀死进程 [英] How to kill a process on no output for some period of time

查看:58
本文介绍了如何在一段时间内无输出地杀死进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个程序,假定它可以运行很长时间,并且将进度输出到 stdout ,但是,在某些情况下,它开始挂起,最简单的方法是重新启动它.

I've written a program that is suppose to run for a long time and it outputs the progress to stdout, however, under some circumstances it begins to hang and the easiest thing to do is to restart it.

我的问题是:是否有一种方法可以做,只有在特定的秒数内没有任何输出时,它才会终止该进程?

My question is: Is there a way to do something that would kill the process only if it had no output for a specific number of seconds?

我已经开始考虑它了,唯一想到的就是这样:

I have started thinking about it, and the only thing that comes to mind is something like this:

./application > output.log &
tail -f output.log

然后创建脚本,该脚本将查看 output.log 上一次修改的日期和时间,然后重新启动整个程序.

then create script which would look at the date and time of the last modification on output.log and restart the whole thing.

但是它看起来非常乏味,如果有现有的命令,我将不愿进行所有操作.

But it looks very tedious, and i would hate to go through all that if there were an existing command for that.

推荐答案

据我所知,没有标准的实用程序可以做到,但是单线的好开始是:

As far as I know, there isn't a standard utility to do it, but a good start for a one-liner would be:

timeout=10; if [ -z "`find output.log -newermt @$[$(date +%s)-${timeout}]`" ]; then killall -TERM application; fi

至少,这将避免编写更复杂的脚本的繁琐部分.

At least, this will avoid the tedious part of coding a more complex script.

一些提示:

  • 使用 find 实用程序将output.log文件的最后修改日期与时间参考进行比较.
  • 时间参考由 date 实用程序返回,作为自 EPOCH (1970-01-01 UTC) 以来以秒为单位的当前时间 (+%s).
  • 使用 bash $ []操作减去$ timeout值(在示例中为10秒)
  • 如果上述 find 没有返回任何输出,则说明文件更改的时间未超过10秒钟.这将在 if 条件下触发true,并执行 killall 命令.
  • Using the find utility to compare the last modification date of the output.log file against a time reference.
  • The time reference is returned by date utility as the current time in seconds (+%s) since EPOCH (1970-01-01 UTC).
  • Using bash $[] operation to subtract the $timeout value (10 seconds on the example)
  • If no output is returned from the above find, then the file wasn't changed for more than 10 seconds. This will trigger a true in the if condition and the killall command will be executed.

您还可以使用以下方法为此设置 alias :

You can also set an alias for that, using:

alias kill_application='timeout=10; if [ -z "`find output.log -newermt @$[$(date +%s)-${timeout}]`" ]; then killall -TERM application; fi';

然后通过发出命令 kill_application

如果要在没有人工干预的情况下自动重新启动应用程序,则可以安装 crontab 条目以每分钟左右运行一次,还可以在 killall (也许您还可能希望将-TERM更改为-KILL,以防应用程序对可处理的信号不响应.

If you want to automatically restart the application without human intervention, you can install a crontab entry to run every minute or so and also issue the application restart command after the killall (Probably you may also want to change the -TERM to -KILL, just in case the application becomes unresponsive to handleable signals).

这篇关于如何在一段时间内无输出地杀死进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆