【问题标题】:java Runtime.getRuntime().exec cannot get output for some commandsjava Runtime.getRuntime().exec 无法获取某些命令的输出
【发布时间】:2014-05-24 19:26:44
【问题描述】:

我在 OSX 10.8.5 上并尝试从 Java 运行终端命令。

因此,使用下面的代码,我可以读取 Runtime.getRuntime().exec 的某些命令的输出,但不能读取其他命令。

你会看到一些命令像 ls 和 ifconfig 一样返回它们的输出,但是尝试让 openssl 返回它的输出要么什么也不返回,要么挂起,具体取决于实现。

我还使用了两种不同的方法来读取输出,但结果相同。

是什么阻止了某些命令返回任何输出?

    theCommand = "ls"; //this command works OK and returns its output

    //theCommand = "ifconfig"; //this command works OK and returns its output

    //theCommand = "openssl rand"; //this command does not return any output

    //theCommand = "/bin/sh openssl rand"; //this command does not return any output

    //theCommand = "/bin/sh -c openssl rand"; //this command hangs

    try {
      System.out.println("trying...");
      Process extProc=Runtime.getRuntime().exec(theCommand);
      extProc.waitFor();

      //READ ouput attempt #1 - this works okay for ls and ifconfig command
      //BufferedReader readProc=new BufferedReader(new InputStreamReader(extProc.getInputStream()));
      //while(readProc.ready()) {
      //  theReadBuffer = readProc.readLine();
      //  System.out.println(theReadBuffer);
      //}

      //READ output attempt #2 - this works okay for ls and ifconfig command
      InputStream theInputStream = extProc.getInputStream();
      java.util.Scanner theScanner = new java.util.Scanner(theInputStream).useDelimiter("\\A");
      if (theScanner.hasNext()) {
          theReadBuffer = theScanner.next();
          System.out.println(theReadBuffer);
      }

    } catch( IOException e) {
      System.out.println(e.getMessage());
    } catch(InterruptedException e) {
      System.out.println(e.getMessage());
    }

我最终试图从这个命令(在终端中工作)生成随机字符:

openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'

谢谢

【问题讨论】:

  • 尝试使用 ProcessBuilder,并在执行前显式设置进程的 redirectErrorStream 选项。可能是进程正在写入 STDErr。
  • 是的,感谢这有帮助,因为问题是它正在写入 getErrorStream 而不是 getInputStream。

标签: java linux macos bash terminal


【解决方案1】:

好的,感谢 Mark W 对原始问题的评论,我意识到有些命令输出到 stderr(使用 getErrorStream),有些输出到 stdout(使用 getInputStream)。

所以做这样的事情可以让你从以下任何一个中读取:

      BufferedReader readInputProc=new BufferedReader(new InputStreamReader(extProc.getInputStream()));
      while(readInputProc.ready()) {
        theReadBuffer = readInputProc.readLine();
        System.out.println(theReadBuffer);
      }
      BufferedReader readErrorProc=new BufferedReader(new InputStreamReader(extProc.getErrorStream()));
      while(readErrorProc.ready()) {
        theReadBuffer = readErrorProc.readLine();
        System.out.println(theReadBuffer);
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2013-01-21
    • 2015-12-09
    • 2011-08-08
    相关资源
    最近更新 更多