Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: The Halting Problem

Bart Schaefer sent me the following 1.0K:

> } This kills the long-running job on timeout, but it also puts the job
> } in the background. Control-C won't kill it.
> You're almost there.  If ctrl+c won't kill the java process in the above
> example, then there's some additional signal handling going on behind
> the scenes, and you just need to add a trap before the "wait"...

Bart, this is great. Thanks!

I've generalized the script so that it takes an arbitrary long-running command through ARGV (like time) and kills it after the specified number of seconds:

  #!/usr/bin/env zsh

  if [[ $# -lt 2 ]]; then
    echo "Usage: $0 nseconds command [arg1 [arg2 ...]]" >&2
    exit 1


  # The command to run is in ARGV[2..]. cmd is going to be embedded in a
  # string, so we'll need to do some quoting of # its elements to ensure
  # correct interpolation.

  # Kills the specified process after nseconds have expired.
  sleepkill() {
    sleep $1
    kill $2
    print "Command $cmd timed out."

  # Start up both the long-running process and a sleep timer. The parentheses
  # are needed to background the entire cmd, not just its last subcommand.
  eval "($cmd) &"

  sleepkill $nseconds $longpid &

  # By default, Control-C will kill the wait that happens below -- and not
  # longpid. I want it to kill longpid and the sleep timer.
    kill $longpid
    kill -HUP -$$

  # If longpid has already finished, wait will flash a message saying it doesn't
  # know about the process. I don't want to see that message.
  wait $longpid 2>/dev/null

  # If longpid finishes before the sleep timer, let's kill the sleep timer.
  kill $sleeppid 2>/dev/null

If you see any improvements that can be made, I welcome input.

Chris Johnson

Messages sorted by: Reverse Date, Date, Thread, Author