有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的子进程再次出现同步问题

我在Ubuntu 14.04上。 我试图通过Java的类ProcessBuilder运行类似ps aux | grep whatevah的东西。我创建了两个子进程,并使它们同步通信,但由于某种原因,我在终端中看不到任何东西

以下是代码:

try {
    // What comes out of process1 is our inputStream
    Process process1   = new ProcessBuilder("ps", "aux").start();
    InputStream is1    = process1.getInputStream();
    BufferedReader br1 = new BufferedReader (new InputStreamReader(is1));

    // What goes into process2 is our outputStream
    Process process2  = new ProcessBuilder("grep", "gedit").start();
    OutputStream os   = process2.getOutputStream();
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

    // Send the output of process1 to the input of process2
    String p1Output  = null;
    while ((p1Output = br1.readLine()) != null) {
        bw.write(p1Output);
        System.out.println(p1Output);
    }
    // Synchronization
    int finish = process2.waitFor();
    System.out.println(finish);

    // What comes out of process2 is our inputStream            
    InputStream is2    = process2.getInputStream();
    BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));

    String combOutput  = null;
    while ((combOutput = br2.readLine()) != null)
        System.out.println(combOutput);

    os.close();
    is1.close();
    is2.close();

} catch (IOException e) {
    System.out.println("Command execution error: " + e.getMessage());
} catch (Exception e) {
    System.out.println("General error: " + e.getMessage());
}

(这个System.out.println(p1Output);只是让我检查一下,需要打印的是最后一个,打印ps aux | grep whatevah的结果。)

我尝试过几种不那么愚蠢的方法,包括:

  • 如果我对process2的所有内容进行注释,就会得到终端上打印的ps aux结果
  • 如果我按原样运行程序,它不会向终端打印任何内容
  • 如果取消对waitFor调用的注释,则只打印ps aux
  • 例如,如果将命令更改为ls -alls -al,那么这两个命令都会被打印出来
  • 我试着把"aux"换成"aux |",但还是没有打印出来
  • 关闭了缓冲区,也什么都没有

等等

任何帮助都将不胜感激。 干杯

编辑

在接受Ryan惊人的回答几分钟后,我最后一次尝试让这段代码正常工作。我成功了!我改变了:

while ((p1Output = br1.readLine()) != null) {
    bw.write(p1Output);
    System.out.println(p1Output);
}

用于:

while ((p1Output = br1.readLine()) != null) {
    bw.write(p1Output + "\n");
    System.out.println(p1Output);
}

bw.close();

而且很有效!我记得之前关闭过缓冲区,所以我不知道出了什么问题。事实证明,为了让一段代码在XD中工作,你不应该一直睡到很晚

不过,瑞安的回答仍然令人惊讶


共 (0) 个答案