-1

I was using bash to run different java programs.

For some programs, there are bugs that will run into infinity loops, so I want to set up time limit like 5 seconds. If the program cannot finish within 5 seconds, the bash script should continue running other programs instead of waiting the current program ends.

I have tried

timeout 5 java <my program>

But still my script won't proceed when it encounters the problematic program.

I have also tried the script providing here: http://www.bashcookbook.com/bashinfo/source/bash-4.0/examples/scripts/timeout3 with no luck that my script still won't proceed.

Another command I have tried was

( /path/to/slow command with options ) & sleep 5 ; kill $!

When I ran my script using above command, it said process id not found when in reality it's still running the problematic program.

I wonder if anyone has tried to timeout a running java program that runs into infinity loops. If so, Please shed some light!

Btw, using ctr+c at the time the program enters infinity loops can make the program stop and the script will proceed to next one.

Sherwood Lee
  • 237
  • 2
  • 4
  • 12

2 Answers2

0

you could create a monitor thread in your java app(s) that, after a certain timeout, kills execution of the java app from "inside".

something like

Thread t = new Thread( new Monitor() );

t.setDaemon( true ); // we want this thread to quit if the enclosing app finishes before it does

t.start();


...

class Monitor
extends Runnable
{
    public void run()
    {
        Date START = new Date();
        boolean timeout = false;

        while( ! timeout )
        {
             Date NOW = new Date();
             timeout = ( NOW.getTime() - START.getTime() >= 5000 );
        }

        System.exit( 1 );
     }
 }
him
  • 608
  • 5
  • 15
  • Thank you for providing a way to solve this. But if possible, I would like to know if there's a way to do it externally. In my case, changing 1000 java programs is not that practical. Still, thank you for the answer! – Sherwood Lee Nov 13 '14 at 23:24
0

A more hacky solution: sleep <your_preferend_timeout> && execute_whatever_you_want_here &

michel9501
  • 120
  • 7
  • this one works partially. At least, I can somehow figure it out how to do it. Thank you! – Sherwood Lee Nov 14 '14 at 15:00
  • Why partially? what's missing? – michel9501 Nov 14 '14 at 17:43
  • When I use the above command. My next command seemed to get skipped one case. I was using diff to see the difference of the output from each program. When I used the above command. Every diff got delayed by one case. I guess I am not quite sure what your command is doing. If you can elaborate more, it would be a big help! – Sherwood Lee Nov 15 '14 at 22:18