How to constraint time a program runs in Linux?

Potential solution #1

Use the timeout command:

$ date
Mon May  6 07:35:07 EDT 2013
$ timeout 5 sleep 100
$ date
Mon May  6 07:35:14 EDT 2013

You can put a guard into the timeout command as well to kill the process if it hasn't stopped after some period of time too.

$ date
Mon May  6 07:40:40 EDT 2013
$ timeout -k 20 5 sleep 100
$ date
Mon May  6 07:40:48 EDT 2013

This will wait up to 20 seconds after the process sleep 100 should've stopped, if it's still running, then timeout will send it a kill signal.

Potential solution #2

An alternative way, though more risky method would be as follows:

./myProgram &
sleep 1
kill $! 2>/dev/null && echo "myProgram didn't finish"

Found this technique on Stack Overflow in a question titled: Limiting the time a program runs in Linux. Specifically this answer.

NOTE: Per a comment left by @mattdm the above method can be risky given it makes the assumption that there hasn't been any new processes started since your process. So no new PIDs have been assigned. Given this, this approach should probably not be used but is here only as a reference for a general approach to the problem. The timeout method is the better option of the 2.


I've found something a little better, than timeout: timelimit.

It has several advantages; one is that user can manually abort execution by pressing "Ctrl+C".

The timelimit program is available in Debian repository.


You can tune cpu time and other things with ulimit, for cpu time particularly:

$ ulimit -t 60      # limit to 60 seconds
$ program