简体   繁体   English

使用非阻塞I / O从Runtime()。exec读取输入

[英]Read input from Runtime().exec with Non-block I/O

It seems that using BufferedReader to read a process's InputStream will somehow result in a block I/O behavior. 似乎使用BufferedReader读取进程的InputStream将以某种方式导致块I / O行为。 And the effect is like the program doesn't get the instant input from the process. 效果就像程序没有从流程中获取即时输入。 I know there are more lines that could be read at that time, but the BufferedReader just keep waiting for sometime then I can finally get the lines updated. 我知道当时可以读取更多行,但是BufferedReader一直在等待一段时间,然后我终于可以更新行了。

Here is the code: 这是代码:

While((str=bufferedReader.readLine()!=null) {
  System.out.println(str);
}

Is there some kinds of method that can keep reading from the process without blocking in the while() condition? 是否有一些方法可以保持读取过程而不会阻塞while()条件? cause the process won't return null or anything.... 导致进程不会返回null或任何东西。

You can read the child process output in a separate thread. 您可以在单独的线程中读取子进程的输出。 Something like this 像这样

static BlockingQueue<String> queue = new LinkedBlockingDeque<>();

public static void main(String[] args) throws Exception {
    Process p = Runtime.getRuntime().exec("cmd /c dir");
    final BufferedReader rdr = new BufferedReader(new InputStreamReader(p.getInputStream()));
    Thread t = new Thread() {
        public void run() {
            try {
                for (String line; (line = rdr.readLine()) != null;) {
                    queue.put(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
    for (;;) {
        String line = queue.poll();
        if (line != null) {
            System.out.println(line);
        } else if (!t.isAlive()) {
            break;
        }
    }
}

You can use the NuProcess library for non-blocking I/O to external processes. 您可以使用NuProcess库对外部进程进行非阻塞I / O。 Consider it a replacement for ProcessBuilder and Process in Java. 考虑它替代了Java中的ProcessBuilderProcess

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

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