0

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

Community
  • 1
  • 1
Caffeinated
  • 11,982
  • 40
  • 122
  • 216

2 Answers2

2

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.

schtever
  • 3,210
  • 16
  • 25
  • Thanks schtever, I will attempt this !! – Caffeinated Jul 19 '15 at 22:45
  • Hey , I got this working like you described.. but just one tiny issue I get. After the program restarts with incremented `globalVar` , because we lose the CMD access suddenly we can't now use `CTRL+C` once again to shut it down a 2nd time. I'll look into that SIGINT – Caffeinated Jul 20 '15 at 00:09
1

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.

Community
  • 1
  • 1
Anthony Raymond
  • 7,434
  • 6
  • 42
  • 59
  • 1
    So that's pretty much a paste and copy of the linked post... – MadProgrammer Jul 19 '15 at 22:25
  • 1
    This is why i provide a link to the source post – Anthony Raymond Jul 19 '15 at 22:26
  • 2
    Or you could have made it a comment or voted to close the question, instead you decided to ride the shirt tales of some one else answer in order to boost your own rep...If you had expended on what the previous answer had stated, quoting it as the source for the ideas, then that would have been a different matter... – MadProgrammer Jul 19 '15 at 22:27