gpt4 book ai didi

java - 无法获取命令执行的值 "lsof"

转载 作者:行者123 更新时间:2023-12-01 11:09:37 25 4
gpt4 key购买 nike

这是我的程序的样子

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

最佳答案

pipe | 是一个问题。下面修复了它

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

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

关于java - 无法获取命令执行的值 "lsof",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32529867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com