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

The Halting Problem



Hi, folks. I have the following interest: I want to run a potentially long-running job interactively from a script, but if this job exceeds a certain duration, I want to kill it and notify the user.

I've read up on traps and the NOTIFY option in From Bash to Z Shell, but I'm stuck. My current non-working proof-of-concept is:

  setopt LOCAL_OPTIONS
  setopt NOTIFY

  sleepkill() {
    sleep 5
    print "timed out"
    kill $$
  }

  sleepkill &

  # Create a consuming task. Let's have Java draw a spinner.
  (cat <<EOF
  public class Foo {
    public static void main(String[] args) {
      for (int i = 0; true; i = (i + 1) % 4) {
        System.out.print("\r" + "\\\\|/-".charAt(i));
      }
    }
  }
  EOF
  ) > Foo.java

  javac Foo.java

  # Here's the long running job. I want it in the foreground so I can
  # kill it manually, observe its output, etc. But if it's taking to
  # long, I want it automatically killed.
  java Foo

When "sleep 5" finishes, the script itself is killed and the JVM process becomes an orphan. Is there a way I can kill the orphan too?

I tried backgrounding the long-running job, capturing its PID, and passing that to sleepkill as the process to kill:

  java Foo &
  longpid=$!

  sleepkill $longpid &
  sleeppid=$!

  wait $longpid
  # Kill the sleep timer, if necessary.
  kill $sleeppid 2>/dev/null

This kills the long-running job on timeout, but it also puts the job in the background. Control-C won't kill it.

I'm thankful for any suggestions!

-- 
Chris Johnson
johnch@xxxxxxxx



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