Differences between revisions 4 and 5
Revision 4 as of 2007-06-18 16:12:40
Size: 1284
Editor: GreyCat
Comment: fix up white space
Revision 5 as of 2008-05-12 15:12:49
Size: 1531
Editor: host-195
Comment:
Deletions are marked like this. Additions are marked like this.
Line 21: Line 21:
This will, as you will soon discover, produce quite a mess regardless of whether the timeout condition kicked in or not.  Cleaning it up is not something worth my time -- just use {{{doalarm}}} or {{{timeout}}} instead. Really. This will, as you will soon discover, produce quite a mess regardless of whether the timeout condition kicked in or not.

The shell-script "[http://www.shelldorado.com/scripts/cmds/timeout timeout]" uses the approach above. It has the advantage of working immediately (no need for compiling a program), but has problems e.g. with programs reading standard input.

Cleaning it up is not something worth my time -- just use {{{doalarm}}} or {{{timeout}}} instead. Really.

Anchor(faq68)

How do I run a command, and have it abort (timeout) after N seconds?

There are two C programs that can do this: [http://pilcrow.madison.wi.us/ doalarm], and [http://www.porcupine.org/forensics/tct.html timeout]. (Compiling them is beyond the scope of this document; suffice to say, it'll be trivial on GNU/Linux systems, easy on most BSDs, and painful on anything else....)

If you don't have or don't want one of the above two programs, you can use a perl one-liner to set an ALRM and then exec the program you want to run under a time limit. In any case, you must understand what your program does with SIGALRM.

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

doalarm ${NUMBER_OF_SECONDS_BEFORE_ALRMING} program arg arg ...

If you can't or won't install one of these programs (which really should have been included with the basic core Unix utilities 30 years ago!), then the best you can do is an ugly hack like:

   command & pid=$!
   { sleep 10; kill $pid; } &

This will, as you will soon discover, produce quite a mess regardless of whether the timeout condition kicked in or not.

The shell-script "[http://www.shelldorado.com/scripts/cmds/timeout timeout]" uses the approach above. It has the advantage of working immediately (no need for compiling a program), but has problems e.g. with programs reading standard input.

Cleaning it up is not something worth my time -- just use doalarm or timeout instead. Really.

BashFAQ/068 (last edited 2019-07-25 13:38:08 by GreyCat)