我尝试使用以下代码执行 Linux 命令。但它没有给出输出,只是打印 exit 1。当我在 Linux 终端上执行命令时,它给出了输出。当通过 Java 执行时,它给出了错误。请建议。
JButton btnRunningtime = new JButton("RunningTime");
btnRunningtime.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
textArea.setText("");
String s2=comboBox.getSelectedItem().toString();
p = Runtime.getRuntime().exec("ps -eo pid,comm,cmd,start,etime | grep -i "+s2);
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
{
textArea.append(s+"\n");
System.out.println("Running time "+s);
}
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
}
});
btnRunningtime.setBounds(409, 211, 104, 27);
contentPane.add(btnRunningtime);
最佳答案
Java 的 Runtime.exec
方法不调用 shell 来执行命令(因此它不同于标准的 C system
调用,例如)。您尝试传递给 exec
的命令是一个 shell 命令,而不是一个简单的可执行进程,您需要一个 shell 才能让它工作。
您需要exec
的东西类似于数组:
["sh", "-c", "ps -eo pid,comm,cmd,start,etime | grep -i "+s2]
尽管您可能必须将第一个参数指定为 "/bin/sh"
。
关于java - 为什么下面的代码在导出 1 处停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23976735/