In my Java code, it simply loops some output and then continues to loop it even if we send CTRL+C
via windows command-line. But issue is that it only works once. After the first iteration of CTRL+C
it looks like we lose the access to the JVM from within the CMD:
import java.text.SimpleDateFormat;
import java.sql.Date;
import sun.misc.SignalHandler;
import sun.misc.Signal;
import java.io.*;
public class SHTest {
static int globalVar = 0;
public static void main ( String[] args ) throws IOException , InterruptedException {
globalVar = Integer.parseInt( args[0] ) ;
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" , "" + globalVar /* + " " + ++globalVar */ }; //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) { }
// while ( true ) { }
}
} ); //end addShutdownHook()
//int copyGlobalVar = globalVar;
while ( true ) {
long currentDateTime = System.currentTimeMillis();
Date date = new Date(currentDateTime);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
System.out.println ( "Looping: " + formattedDate + " : " + globalVar );
Thread.sleep ( 1000 );
}
}
}
thanks !
References:
Sending Signals to a Running JVM
How can I "intercept" Ctrl+C in a CLI application?
How to make a Java program that cannot be killed from command line?