命令行命令在一定时间后自动删除命令 [英] Command line command to auto-kill a command after a certain amount of time

查看:275
本文介绍了命令行命令在一定时间后自动删除命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一定时间后自动杀掉命令。我记得这样的界面:

I'd like to automatically kill a command after a certain amount of time. I have in mind an interface like this:

% constrain 300 ./foo args

这将使用args运行./foo,但是如果它在5分钟后仍然运行,则会自动终止。

Which would run "./foo" with "args" but automatically kill it if it's still running after 5 minutes.

将概念推广到其他约束可能是有用的,例如,如果它使用了太多的内存,自动杀死进程。

It might be useful to generalize the idea to other constraints, such as autokilling a process if it uses too much memory.

添加:Jonathan的解决方案正是我的想法,它的工作原理像linux上的魅力,但是,我不能让它在Mac OSX上工作。我摆脱了SIGRTMIN,它让它编译正常,但信号只是不被发送到子进程。任何人都知道如何在Mac上进行此操作?

ADDED: Jonathan's solution is precisely what I had in mind and it works like a charm on linux, but I can't get it to work on Mac OSX. I got rid of the SIGRTMIN which lets it compile fine, but the signal just doesn't get sent to the child process. Anyone know how to make this work on Mac?

[添加:请注意,Jonathan可以在Mac和其他地方使用更新。]

[Added: Note that an update is available from Jonathan that works on Mac and elsewhere.]

推荐答案

我已经到了晚会,但我没有看到我最喜欢的技巧列在答案。

I've arrived rather late to this party, but I don't see my favorite trick listed in the answers.

在* NIX下,一个报警(2) execve(2)并且SIGALRM默认是致命的。所以,你可以简单地:

Under *NIX, an alarm(2) is inherited across an execve(2) and SIGALRM is fatal by default. So, you can often simply:

$ doalarm () { perl -e 'alarm shift; exec @ARGV' "$@"; } # define a helper function

$ doalarm 300 ./foo.sh args

或安装琐碎的C包装来为您执行此操作。

or install a trivial C wrapper to do that for you.

优点只涉及一个PID,机制很简单。如果 ./ foo.sh 退出太快并重新使用其PID,则不会杀死错误的进程。

Advantages Only one PID is involved, and the mechanism is simple. You won't kill the wrong process if, for example, ./foo.sh exited "too quickly" and its PID was re-used. You don't need several shell subprocesses working in concert, which can be done correctly but is rather race-prone.

缺点时间 - 时间 - 受限进程不能操作其闹钟(例如, alarm(2) ualarm(2) setitimer(2)),因为这可能会清除继承的报警。显然,它也不能阻止或忽略SIGALRM,尽管对于一些其他方法也可以这样说SIGINT,SIGTERM等。

Disadvantages The time-constrained process cannot manipulate its alarm clock (e.g., alarm(2), ualarm(2), setitimer(2)), since this would likely clear the inherited alarm. Obviously, neither can it block or ignore SIGALRM, though the same can be said of SIGINT, SIGTERM, etc. for some other approaches.

有些)系统以 alarm(2)的方式实现 sleep(2),甚至今天,一些程序员使用 alarm(2)作为I / O和其他操作的粗略内部超时机制。然而,根据我的经验,这种技术适用于您想限制时间的绝大多数流程。

Some (very old, I think) systems implement sleep(2) in terms of alarm(2), and, even today, some programmers use alarm(2) as a crude internal timeout mechanism for I/O and other operations. In my experience, however, this technique is applicable to the vast majority of processes you want to time limit.

这篇关于命令行命令在一定时间后自动删除命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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