Processbuilder without redirecting StdOut

2019-02-23 08:09发布

问题:

Is it possible to redirect the output stream back into a process, or not redirect it at all?

The backstory: I am trying to launch an executable using processbuilder. (Source dedicated server / srcds.exe to be exact)

As a result of launching it with the processbuilder, the console window of this executable remains empty. A few seconds after launch, the executable crashes with the error "CTextConsoleWin32::GetLine: !GetNumberOfConsoleInputEvents" because its console is empty.

回答1:

I think you're talking about making the launched process' stdout go to the current process' stdout. If you're using JDK7, that's as simple as:

.redirectOutput(ProcessBuilder.Redirect.INHERIT)

Update: (too much for a comment) I think you're confused. When you launch a process from a terminal, the process becomes a child of that terminal process, and the stdout is sent to that terminal. When you launch a process from Java, then the process is a child of the Java process, and its stdout goes to Java.

In the first case, there's a terminal showing stdout because you launched it from a terminal yourself, and that's what terminals do with stdout. When launching from Java, however, there wouldn't be a terminal window unless something in the process you launched opened a terminal, and stdout of the process you launched is handed back to you, the programmer, to do with as you will. The equivalent behavior to what you see when launching from a terminal is the Redirect.INHERIT that I already mentioned.

Your problem right now isn't Java. Your problem is not understanding how this "srcds.exe" expects stdin and stdout to be handled. Figure that out, and then come back and ask how to do that with Java.

I'm just guessing now, but you could try reading from the process' stdout and feeding it back into the stdin. Maybe that's what it's expecting? That sounds crazy, though.



回答2:

you can get the output like this

ProcessBuilder pb = new ProcessBuilder(args);
Process p = pb.start(); 

//below code gets the output from the process
InputStream in = p.getInputStream();
BufferedInputStream buf = new BufferedInputStream(in);
InputStreamReader inread = new InputStreamReader(buf);
BufferedReader bufferedreader = new BufferedReader(inread);
String line;
while ((line = bufferedreader.readLine()) != null) {
    *do something / collect output*
}