问题
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
回答1:
The static variable globalVar
will not survive the destruction and recreation of the process. In the new process, it will be reinitialized to 0. It should be passed as a parameter to the process, and globalVar
should then be initialized to the value of that argument.
回答2:
Runtime.getRuntime ().addShutdownHook
is called before the JVM stops the program, but it does not prevent from stopping it.
If you want to intercept SIGINT signals, you'll need to use a SignalHandler
(sun.misc.SignalHandler) on Unix as well as on Windows.
See this article (pdf, page 8 and 9).
Here is a simple example on how to use it :
Signal.handle(new Signal("INT"), new SignalHandler () {
public void handle(Signal sig) {
if (globalVar == 9) {
System.out.println("9 lifes consumes, program will shutdown");
System.exit();
}
System.out.println(globalVar + " lifes consumed, one more will be consumed");
// increment your score here
}
});
Source : this post.
来源:https://stackoverflow.com/questions/31506485/how-to-make-a-java-program-that-cannot-be-killed-from-command-line