This question already has an answer here:
- How can I “intercept” Ctrl+C in a CLI application? 4 answers
I am trying to run a Java program that appears to have "9 lives". It simply prints out, in an infinite loop, the following when we run it:
GlobalVar = 1
GlobalVar = 1
GlobalVar = 1
/* etc */
GlobalVar = 1
GlobalVar = 1
Then once we CTRL+C
and kill the program, rather than quitting and going to the command prompt ... it should continue anew like this:
GlobalVar = 2
GlobalVar = 2
GlobalVar = 2
And on and on, it should re-open with the GlobalVar
set to 3, 4, 5 etc.
Firstly, I know that This code is slightly impractical - it is just for academic exercise. But I am learning the Java.
Here my code so far :
import java.io.*;
public class SHTest {
static int globalVar = 0;
public static void main ( String[] args ) throws IOException , InterruptedException {
System.out.println ("The Global Var is " + globalVar);
Runtime.getRuntime ().addShutdownHook ( new Thread () {
@Override
public void run () {
globalVar += 1;
/* shutdown */
String[] command = {"C://Program Files//Java//jdk1.7.0_02//bin//java.exe", "SHTest"}; //args[0] ... CreateTexts
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
try {
Process exec = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
System.out.println("Process exited with " + exec.waitFor());
}
catch(IOException io) { }
catch(InterruptedException inter) { }
}
} ); //end addShutdownHook()
//int copyGlobalVar = globalVar;
while ( true ) {
System.out.println ( "Looping " + globalVar );
Thread.sleep ( 800 );
}
}
}
Reference:
Capture SIGINT in Java
Why can't I re-execute a Java program from within an Exception block?
addShutdownHook method
NOTE: I am open to using windows batch files as the JVM seems to have its own limitations with these things. Or other tools too. Even for Linux OS , would be Ok