timeout: send a signal to a process after some time

September 20th, 2009 edited by Vicho

Article submitted by Carsten Aulbert. Guess what? We still need you to submit good articles about software you like!

timeout (part of the SATAN package) is a nice little tool to terminate/send a signal to a process after a given time.

It usually takes two arguments, the first one is the time limit in seconds and the second the program to start. All trailing options are then passed to the started program.

It accepts a single numerical option which specifies what signal to send — be careful as its default is SIGKILL.

Quite useful on many occasions, e.g.: strace stats of a process PID for the next 300 seconds

timeout -2 300 strace -tt -c -p PID

Ensure that your kids don’t play childsplay all day long (of course you need to make sure that they won’t be able to restart it ;))

timeout 3600 childsplay

Similar programs could be timelimit.

Package is available in Debian for ages (at least since etch) and Ubuntu since at least dapper.

Posted in Debian, Ubuntu |

5 Responses

  1. Steven Pigeon Says:

    the Bash ulimit command does the same thing:

    ( ulimit -t 3600; childsplay )

    creates a sub-shell with modified CPU time limit of 3600s that launches childsplay. Setting up a bash function or script as:

    ( ulimit -t $1 ; $2 ${@:3} )

    can also be used as a replacement. (it would also need to check if all the arguments are set, etc., etc. $1 is the first argument, $2 the second, of course, and ${@:3}$ is all the arguments, starting from the third (so basically, the rest of the command line))

    btw, I’ve been a long time debaday reader, keep up the good work!

  2. Vicho Says:

    Not it’s not the same. ulimit -t measures time in CPU. So if a process doesn’t consume CPU, it doesn’t timeout. For example,

    (ulimit -t 3; sleep 10)

    takes 10 seconds to execute, but

    timeout 3 sleep 10

    takes only the expected 3 seconds.

    Thanks for the cheer up!

  3. Steven Pigeon Says:

    You’re quite right! I forgot about programs that are 99.999% idle… I suppose a lot of games are like that.

    I used ulimit -St x -t y recently to limit a compute-intensive program and it works pretty well.

    How does that program works? It forks then keep walltime and eventually kill the child process?

  4. Vicho Says:

    That’s right, it forks and execs the command. The parent installs a signal handler for a bunch of signals (including SIGALRM) and then, it sleeps in an alarm(time). When the alarm fires (or any of the other “terminate” signals are caught), the parent sends the signal (SIGKILL by default) to the command and returns the exit status of the command.

  5. JM Says:

    If you want to limit the overall children session duration, you should probably use timeoutd instead (with a final D). Unfortunately you’ll have to apply a patch to make it run correctly in Lenny but it is easy to do: