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
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.
Are there any existing tools that do that, or has anyone written such a thing?
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?
[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.
Under *NIX, an
alarm(2)is inherited across anexecve(2)and SIGALRM is fatal by default. So, you can often simply:or install a trivial C wrapper to do that for you.
Advantages Only one PID is involved, and the mechanism is simple. You won’t kill the wrong process if, for example,
./foo.shexited “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.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.Some (very old, I think) systems implement
sleep(2)in terms ofalarm(2), and, even today, some programmers usealarm(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.