无法获得命令执行的价值" lsof"

时间:2015-09-11 18:24:27

标签: java lsof

这是我的程序的样子

Reference

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecuteShellCommand {

  public static void main(final String[] args) {

    final ExecuteShellCommand obj = new ExecuteShellCommand();
    final String ping = "ping -c 3 google.com";
    final String lsof = "lsof | wc -l";
    final String output = obj.executeCommand(ping);
    System.out.println(output);
  }

  private String executeCommand(final String command) {
    final StringBuffer output = new StringBuffer();
    final Process p;
    try {
      p = Runtime.getRuntime().exec(command);
      final int waitForStatus = p.waitFor();
      System.out.println("waitForStatus=" + waitForStatus);
      final BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line = "";
      while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
      }
    } catch (final Exception e) {
      e.printStackTrace();
    }
    return output.toString();
  }
}

当我运行此程序时,我的输出是什么

Process finished with exit code 0

但是,当我在我的机器上运行相同的命令时,我看到了

$ lsof | wc -l
    8045

这里有什么问题?

更新 当我以命令运行final String ping = "ping -c 3 google.com";时,我将输出视为

waitForStatus=0
PING google.com (216.58.192.14): 56 data bytes
64 bytes from 216.58.192.14: icmp_seq=0 ttl=59 time=7.412 ms
64 bytes from 216.58.192.14: icmp_seq=1 ttl=59 time=8.798 ms
64 bytes from 216.58.192.14: icmp_seq=2 ttl=59 time=6.968 ms

--- google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 6.968/7.726/8.798/0.779 ms

但是对于final String lsof = "lsof | wc -l";,我得到了

waitForStatus=1


Process finished with exit code 0

2 个答案:

答案 0 :(得分:1)

您不应该使用Runtime.exec。十多年来它已经过时了。它的替换是ProcessBuilder

正如您所发现的,您无法传递管道(或任何重定向),因为它不是命令的一部分;它的功能由shell提供。

但是,您根本不需要管道。 Java在做同样的工作方面做得很好:

long count;

ProcessBuilder builder = new ProcessBuilder("lsof");
builder.inheritIO().redirectOutput(ProcessBuilder.Redirect.PIPE);

try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(builder.start().getInputStream())) {
    count = reader.lines().count();
}

答案 1 :(得分:0)

管道|是一个问题。以下修好了

final String[] lsof = {
        "/bin/sh",
        "-c",
        "lsof | wc -l"
    };

已回答https://stackoverflow.com/a/5928316/379235