Command line command to auto-kill a command after

2019-01-02 17:58发布

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

15条回答
与风俱净
2楼-- · 2019-01-02 18:24

How about using the expect tool?

## run a command, aborting if timeout exceeded, e.g. timed-run 20 CMD ARGS ...
timed-run() {
  # timeout in seconds
  local tmout="$1"
  shift
  env CMD_TIMEOUT="$tmout" expect -f - "$@" <<"EOF"
# expect script follows
eval spawn -noecho $argv
set timeout $env(CMD_TIMEOUT)
expect {
   timeout {
      send_error "error: operation timed out\n"
      exit 1
   }
   eof
}
EOF
}
查看更多
有味是清欢
3楼-- · 2019-01-02 18:25

Perl one liner, just for kicks:

perl -e '$s = shift; $SIG{ALRM} = sub { print STDERR "Timeout!\n"; kill INT => $p }; exec(@ARGV) unless $p = fork; alarm $s; waitpid $p, 0' 10 yes foo

This prints 'foo' for ten seconds, then times out. Replace '10' with any number of seconds, and 'yes foo' with any command.

查看更多
旧时光的记忆
4楼-- · 2019-01-02 18:29

Isn't there a way to set a specific time with "at" to do this?

$ at 05:00 PM kill -9 $pid

Seems a lot simpler.

If you don't know what the pid number is going to be, I assume there's a way to script reading it with ps aux and grep, but not sure how to implement that.

$   | grep someprogram
tony     11585  0.0  0.0   3116   720 pts/1    S+   11:39   0:00 grep someprogram
tony     22532  0.0  0.9  27344 14136 ?        S    Aug25   1:23 someprogram

Your script would have to read the pid and assign it a variable. I'm not overly skilled, but assume this is doable.

查看更多
登录 后发表回答