Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a process with inherited stdin/stdout/stderr in Java 6

If I start a process via Java's ProcessBuilder class, I have full access to that process's standard in, standard out, and standard error streams as Java InputStreams and OutputStreams. However, I can't find a way to seamlessly connect those streams to System.in, System.out, and System.err.

It's possible to use redirectErrorStream() to get a single InputStream that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C system() call.

This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of isatty() in the child process carries through the redirection.

like image 610
John Calsbeek Avatar asked Sep 13 '08 03:09

John Calsbeek


1 Answers

You will need to copy the Process out, err, and input streams to the System versions. The easiest way to do that is using the IOUtils class from the Commons IO package. The copy method looks to be what you need. The copy method invocations will need to be in separate threads.

Here is the basic code:

// Assume you already have a processBuilder all configured and ready to go final Process process = processBuilder.start(); new Thread(new Runnable() {public void run() {   IOUtils.copy(process.getOutputStream(), System.out); } } ).start(); new Thread(new Runnable() {public void run() {   IOUtils.copy(process.getErrorStream(), System.err); } } ).start(); new Thread(new Runnable() {public void run() {   IOUtils.copy(System.in, process.getInputStream()); } } ).start(); 
like image 90
John Meagher Avatar answered Sep 20 '22 12:09

John Meagher