Search code examples
javaconsoleprocessbuilder

Why doesn't the Java console show when using ProcessBuilder?


I use the following to launch a Java application from another Java app.

    ProcessBuilder pb = new ProcessBuilder(javaPath + javaCommand, maxMemStr,
            minMemStr, stackSizeStr, jarCommand, jarfile, jarArg);
    try {
        Process p = pb.start();
    } catch (IOException ex) {
        Logger.getLogger(launch.class.getName()).log(Level.SEVERE, null, ex);
    }

where javaCommand is either java or javaw (javaPath is empty most of the time unless a user points to an alternate path). The problem is, after the app launches, even when I verify the process list to contain java, it doesn't show the console.

Is it because PrcoessBuilder doesn't invoke the command shell? Is there a way to show the console programatically?

Thanks in advance.


Solution

  • This is because the "command console" itself is a process that attaches to the std-in/-out/-err streams of another process and displays them on the screen. When you launch Java all by itself, no other processes will be handling those streams, hence the lack of a command console. To get the results you want, you will need to launch a new instance of the command console and subsequently have it run your custom java command.

    There may be a better way to do this... but I think the solution to this is going to be platform-dependent. In Windows, you could do something like:

    ProcessBuilder pb = new ProcessBuilder("start", "\"JAwesomeSauce\"", "cmd.exe",
        "/k", javaPath + javaCommand, maxMemStr, minMemStr, stackSizeStr, jarCommand,
        jarfile, jarArg);
    try {
        Process p = pb.start();
    } catch (IOException ex) {
        Logger.getLogger(launch.class.getName()).log(Level.SEVERE, null, ex);
    }
    

    I assume you could do something similar in Linux/Mac if that's the O/S you're using.