0

Is it possible to kill a java program's execution from terminal automatically after specific amount of time (when running not compiling). For example, I like to stop the following after 10 seconds:

java examples.Example
razm
  • 25
  • 1
  • 7

1 Answers1

2

If you don't need to watch the output of the process:

#!/bin/bash
{
    java examples.Example >/some/place.log &
    echo $!
    wait $!
} | {
    sleep 10
    kill $(read PID; echo $PID)
}

This script will launch your process in a subshell, transmit its PID to the waiting subshell, which will wait for 10 seconds and kill it.

If you know that your process will always take longer than 10 seconds, you can simply do this:

java examples.Example >/some/place.log &
sleep 10
kill $!
Sir Athos
  • 9,403
  • 2
  • 22
  • 23
  • There's no need for the pipe. The `sleep`/`kill` process neither needs nor cares about the standard output of the other command. – chepner Feb 14 '17 at 19:29
  • @chepner the pipe is so that the first subshell can echo the PID to the second. It also allows parallel creation of the two subshells. – Sir Athos Feb 14 '17 at 19:30
  • 1
    It doesn't need to. `java ... & java_pid=$!; (sleep 10; kill $java_pid) &`. – chepner Feb 14 '17 at 19:37
  • @chepner My intent was to make the main script wait for *up to* 10 seconds (if the first subshell finishes early, it would create a broken pipe condition and cause the second subshell to stop blocking before the 10 seconds are up). – Sir Athos Feb 14 '17 at 19:47