使用此代码并出现错误: 尝试 { 进程 p = Runtime.getRuntime().exec(“(lsof -i:10723 | grep node | awk ‘{print $2;}’)“);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
String s = null;
System.out.println(“Here is the standard output of the command:\n”);
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println(“Here is the standard error of the command (if any):\n”);
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
最佳答案
问题是你不能这样做:
exec("(lsof -i:10723 | grep node | awk '{print $2;}')");
exec
方法不理解 shell 语法。它将将该命令字符串拆分为命令名称和看到空格的参数。
因此 exec
尝试执行的命令名称是 (lsof
...,该命令不存在。因此出现错误消息。
如果你想使用exec
运行管道,简单的方法是使用shell;例如
exec(new String[] {"sh", "-c",
"(lsof -i:10723 | grep node | awk '{print $2;}')"})
关于java - 每当我从代码执行终端命令时,它都会给出 "cannot run program"错误=2 没有这样的文件或目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48398871/