Ravul
Ravul

Reputation: 285

ProcessBuilder running processes in foreground

I want to run an executable written in C++ and to see the cmd promt associated with it in foreground, since the executable prints some lines in the cmd.

I have written the following code, but all processes are created and run in background (In this code I open the dummy cmd.exe process, not my process).

Process p = new ProcessBuilder("C:\\Windows\\System32\\cmd.exe").start();

How can i enable foreground running of processes?

Thanks!

Upvotes: 3

Views: 4151

Answers (2)

Vivin Paliath
Vivin Paliath

Reputation: 95528

The issue is not whether the process is in the foreground or background. When you start a process using Java, you have to use Java to control that process' lifecyle. The Java API provides you access to various attributes of the process. What you're interested in here is the output of the process. That is represented by the process' InputStream. It seems counterintuitive, but it makes sense because from the perspective of your Java program, the process' output is the program's input. Conversely, if you need to send data to the process, you write to the process' OutputStream.

To sum up, access the process' InputStream and print that out to the command-line:

Process process = new ProcessBuilder("C:\\Path\\To\\My\\Application.exe").start();

BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

StringBuilder output = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    output.append(line);
}

System.out.println(line);

This code, of course, assumes that your process is not waiting for any input, i.e., it is not interactive.

Upvotes: 3

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

Vivin Paliath's answer is really the way to go, then you can do whatever you want with the output, display it in your own dialogue, log it, interpret it, check for errors or whatever.

But just in case you really want that command window showing up. Execute cmd.exe and get the process' OutputStream and write the command (application.exe) to it ending with a new line.

Something along the lines of:

Process p = new ProcessBuilder("C:\\Windows\\System32\\cmd.exe").start();
out = p.getOutputStream();
out.write("path\\application.exe\r\n".getBytes());
out.flush();

Should usually drain the input stream too though anyway.

Upvotes: 0

Related Questions