简体   繁体   English

ProcessBuilder创建的Java进程之间的通信

[英]Communication between Java processes created by ProcessBuilder

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).我有一个程序(主类),它创建一个新进程并使用 BufferedReader 从它接收消息(消息通过 ProcessTest 中的 System.out 发送)。

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.但是,我还需要从 Main 向 ProcessorTest 发送消息,但不知道该怎么做。 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:我有一个在 Main 中使用 BufferedWriter 的想法,但不知道它是否可以工作以及是否可以在 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???也许有人通过重定向标准 output 知道什么是正确的通信方式???

When one process runs another process, there are two processes.当一个进程运行另一个进程时,就有两个进程。 The parent process uses ProcessBuilder to create and start a Process .父进程使用 ProcessBuilder 创建和启动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.但是stdin是子进程读取的stream,所以它是父进程的OutputStream。 And so on.等等。

If you are trying to use a BufferedWriter use flush() to ensure a message gets actually sent and does not hog in the buffer.如果您尝试使用 BufferedWriter 使用 flush() 来确保消息被实际发送并且不会占用缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM