Created
November 19, 2015 18:48
-
-
Save DV8FromTheWorld/c4e28dfda56c25ae2e4c to your computer and use it in GitHub Desktop.
Testing process IO Handling to preserve IO between parent/child when child dies.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package net.dv8tion.test; | |
| import java.io.File; | |
| import java.io.IOException; | |
| import java.io.UnsupportedEncodingException; | |
| import java.net.URLDecoder; | |
| public class Main | |
| { | |
| private static final String WAIT_ON_INSTANCE = "wait"; | |
| private static final String NO_WAIT_ON_INSTANCE = "ignore"; | |
| private static final String SECOND_INSTANCE_IDENTIFIER = "second"; | |
| public static void main(String[] args) throws IOException, InterruptedException | |
| { | |
| if (args.length == 0) | |
| { | |
| printErrorMessage(); | |
| } | |
| else if (args[0].equals(SECOND_INSTANCE_IDENTIFIER)) | |
| { | |
| while (true) | |
| { | |
| System.out.println("I am here!"); | |
| Thread.sleep(1000); | |
| } | |
| } | |
| else if (args[0].equals(WAIT_ON_INSTANCE) || args[0].equals(NO_WAIT_ON_INSTANCE)) | |
| { | |
| relaunch(args[0].equals(WAIT_ON_INSTANCE)); | |
| } | |
| else | |
| { | |
| printErrorMessage(); | |
| } | |
| } | |
| public static File getThisJarFile() throws UnsupportedEncodingException | |
| { | |
| //Gets the path of the currently running Jar file | |
| String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath(); | |
| String decodedPath = URLDecoder.decode(path, "UTF-8"); | |
| return new File(decodedPath); | |
| } | |
| private static void relaunch(boolean wait) throws IOException, InterruptedException | |
| { | |
| String[] command = new String[] {"java", "-jar", Main.getThisJarFile().getPath(), SECOND_INSTANCE_IDENTIFIER}; | |
| ProcessBuilder processBuilder = new ProcessBuilder(command); | |
| processBuilder.inheritIO(); //Tells the new process to use the same command line as this one. | |
| Process process = processBuilder.start(); | |
| if (wait) | |
| { | |
| process.waitFor(); | |
| } | |
| System.out.println("Original is ending here!"); | |
| } | |
| private static void printErrorMessage() throws UnsupportedEncodingException | |
| { | |
| System.out.println("Relaunch using one of the argument versions:"); | |
| System.out.printf("java -jar %s %s\nOR\njava -jar %s %s\n", | |
| Main.getThisJarFile().toPath(), WAIT_ON_INSTANCE, | |
| Main.getThisJarFile().toPath(), NO_WAIT_ON_INSTANCE); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment