0

I'm looking for the simplest way to run a command in a shell and kill it if it doesn't end in less than a second of CPU time. Something like:

$ deadline -- slow-foo
Started fooing...
[deadline] 1 sec deadline hit, killing and returning -1!

$ deadline -- quick-foo
Started fooing...
Finished fooing!

A linux-based solution is more than enough, but more portable ones are welcome.

joao
  • 3,517
  • 1
  • 31
  • 43

3 Answers3

3

Coreutils has a timeout utility that does just that, should be available on most Linux distributions:

timeout - run a command with a time limit

Has options for what signal to use and a few other things.

Mat
  • 202,337
  • 40
  • 393
  • 406
3

In addition of timeout(1) given in Mat's answer, and if you want to limit CPU time (not idle time or real time), you could use the setrlimit(2) syscall with RLIMIT_CPU (if the CPU time limit is exceeded, your process gets first a SIG_XCPU signal -which it could catch and handle-, and later a SIG_KILL -uncatchable- signal). This syscall is available in bash(1) with the ulimit builtin.

So to limit CPU time to 90 seconds (i.e. 1 minute and 30 seconds) type

 ulimit -t 90

in your terminal (assuming your shell is bash; with zsh use limit cputime 90, etc...) - then all further commands are constrained by that limit

Read also the instructive time(7) and signal(7) man pages, and Advanced Linux Programming

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

This is quick and dirty and doesn't require any software packages to be installed, so is portable:

TIMEOUT=1
YOURPROGRAM & PID=$! ; (sleep $TIMEOUT && kill $PID 2> /dev/null & ) ; wait $PID
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432