Command line command to auto-kill a command after a certain amount of time

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.]


Solution 1:

GNU Coreutils includes the timeout command, installed by default on many systems.

https://www.gnu.org/software/coreutils/manual/html_node/timeout-invocation.html

To watch free -m for one minute, then kill it by sending a TERM signal:

timeout 1m watch free -m

Solution 2:

Maybe I'm not understanding the question, but this sounds doable directly, at least in bash:

( /path/to/slow command with options ) & sleep 5 ; kill $!

This runs the first command, inside the parenthesis, for five seconds, and then kills it. The entire operation runs synchronously, i.e. you won't be able to use your shell while it is busy waiting for the slow command. If that is not what you wanted, it should be possible to add another &.

The $! variable is a Bash builtin that contains the process ID of the most recently started subshell. It is important to not have the & inside the parenthesis, doing it that way loses the process ID.