Search code examples
javaprocessbuilder

Why can't I re-execute a Java program from within an Exception block?


I'm trying to run the following Java code which is supposed to automatically restart itself when I kill it via CTRL + C on windows command-line :

import java.net.*;
import java.io.*;

public class LineRunner extends Thread {

    public static void main(String[] args) throws InterruptedException, IOException{

        try {

          for (int i = 0; i<10000000; i++) {
          Thread.sleep(200);
          System.out.print("hithe");
        }
        }
        catch(  InterruptedException ioex) {

             String[] command = {"C://Program Files//Java//jdk1.7.0_02//bin//java.exe", "LineRunner"};  
             ProcessBuilder pb = new ProcessBuilder(command);
             pb.redirectErrorStream(true);
             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());

        }
    }
}

But when I kill from command line (via CTRL + C ) , it does not restart the program as I wish.

Any tips appreciated, thanks


Solution

  • Ctrl-C will exit the JVM as has already been discussed in comments.