1

I have a sample.sh script:

#!/bin/sh

echo "start";
exec java -jar myjar.jar
echo "finished successfully";

how can I add timeout to exec java -jar myjar.jar command? After 10 seconds java program should be terminated and there should be printed: "FAIL: Timed out after java -jar myjar.jar" on the std output.

Maad Maad
  • 63
  • 1
  • 7
  • 1
    Don't use `exec`; that *replaces* the current process with the Java program, rather than suspending it until the Java program completes. Either the `exec` succeeds, and `echo "finished..."` *never* executes, or the `exec` fails, `java` never runs, and `echo "finished..."` execute *immediately*. – chepner Sep 18 '19 at 15:57
  • Use ``timeout``. Something like ``if timeout 10 sleep 5 ; then ; echo "success" ; else ; echo "fail" ; fi``. Use your ``java ...`` instead of ``sleep 5``. – Rolf Sep 27 '19 at 05:11

2 Answers2

0

You may start java in background and terminate it after 10 seconds with kill:

echo "start";
exec bash -c 'java -jar myjar.jar && echo "finished successfully"' &
sleep 10 && (kill %1 && echo "Terminated" || echo "Nothing killed")

But in this case your script will always run 10 seconds.

chepner
  • 497,756
  • 71
  • 530
  • 681
user2986553
  • 121
  • 3
0

You could start a process in the background that waits for a certain amount of time and then kills the parent. The parent just needs to kill the process as soon as it finishes the actual job.

For example:

#!/bin/sh

# remember PID of main process
main_pid=$$

kill_after() {
    sleep 3
    echo "Killing after 3 seconds of idle."
    kill ${main_pid}
}

# start kill process and remember killer PID
kill_after &
killer=$!

# your main process (for testing, `sleep 5`)
#java -jar myjar.jar
sleep 5

# kill killer so it doesn't attempt to kill the main
# process anymore
kill $killer

Note that $$ returns the PID of the current process and $! returns the PID of the just launched procedure (kill_after in this case).

nemo
  • 55,207
  • 13
  • 135
  • 135