Communication between Java processes created by ProcessBuilder

Viewed 21

I have a program(Main class), which creates a new Process and receives messages from it using BufferedReader (messages are send throught System.out in ProcessTest).

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder("java", "com.company.ProcessTest");
        pb.directory(new File("some path"));
        Process p = pb.start();

        try (var reader = new BufferedReader(
                new InputStreamReader(p.getInputStream()))) {

            String line = null;
            while (true) {
                if (!reader.ready()) {    
                    Thread.sleep(500);
                } else {
                    line = reader.readLine();
                    System.out.println(line);
                }

            }
        }
    }
}

public class ProcessTest {
    public static void main(String[] args) throws InterruptedException, IOException {
        System.out.println("Hello from ProcessTest");
    }
}

However, I also need to send messages from Main to ProcessorTest and have no idea how to do it. I had an idea of using BufferedWriter in Main but have no idea if it will work and if it possible to receive a message in ProccessTest:

var writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write("Some message");
writer.newLine();
writer.flush();

Maybe someone knows what is the correct way of communication by redirecting standard output?

1 Answers

When one process runs another process, there are two processes. The parent process uses ProcessBuilder to create and start a Process.

This process has stdin, stderr and stdout available like so:

The naming may look strange. But stdin is the stream where the child process reads, so it would be an OutputStream for the parent process. And so on.

In the child process, you can read from System.in and write to System.out and System.err.

If you are trying to use a BufferedWriter on either side use flush() to ensure a message gets actually sent and does not hog in the buffer.

Related