java - 如何让管道命令也返回 Java exec 中的输出?

标签 java linux fedora

当我应用命令命令时,我没有得到任何输出。如何在使用命令时获得输出或两种情况下都不获得输出?

public class test 
{

  public static void main(String args[])
  {
    System.out.println(
        systemtest("ifconfig | awk 'BEGIN { FS = \"\n\"; RS = \"\" } { print $1 $2 }' | sed -e 's/ .*inet addr:/,/' -e 's/ .*//'"));   

  }

  public static String systemtest(String cmds)
  {
    String value = "";
    try 
    { 
      String cmd[] = {
        "/bin/sh",
        "-c",
        cmds
      };       
      Process p=Runtime.getRuntime().exec(cmd); 
      // Try 0: here? wrong
      //p.waitFor(); 
      BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
      String line=reader.readLine(); 
      // Try 1: here?
      //p.waitFor(); 
      while(line!=null) 
      { 
        value += line + "\n";
        line=reader.readLine(); 
      } 
      // Try 2: here?
      p.waitFor(); 
    } catch(IOException e1) {

    } catch(InterruptedException e2) {

    } 

    return value;
  }

最佳答案

在调用 p.waitFor() 之前,您需要读取命令的输出。

事实:

  • 外部命令的输出通过操作系统级“管道”传送。
  • 管道的缓冲量有限。
  • 如果某个生产者进程尝试写入“已满”的管道,该进程将被迫等待,直到消费者进程从管道中读取了一些数据。

(从上述事实中)不难看出,如果外部应用程序产生的输出多于管道缓冲区(在操作系统空间中)所能容纳的输出,那么应用程序的编写方式将导致死锁。

(即使这不是这次问题的真正原因,其他时候也可能是这样。在读取/写入外部进程时请注意死锁。)

关于java - 如何让管道命令也返回 Java exec 中的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8034939/

相关文章:

java - 程序运行时继续读取输入

java - Mongodb 将值列表插入为单独的文档

linux - 通过终端在 Raspberry pi 中同时运行多个 cmdline 命令或文件

java - Linux : How to check a file copy has finished in my watch folder?

emacs - 为什么我的框架标题格式不起作用?

linux - Fedora 中的多线程

ruby-on-rails - 在 Rails 上安装 ruby​​ 时遇到问题

java - 将最大和最小 JVM 堆大小设置为相同是否很好?

java - BufferedReader 就绪方法

linux - 查找和替换 Shell 命令