最近写的一个程序要在Linux下用到Runtime.getRuntime().exec(command),可是发现一个奇怪的问题。先看看代码:
public static void main(String[] args) {
try {
String[] command = {"kill", "-9", "`ps -ef | grep '程序名' | awk '{print $2}'`"};
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
System.out.println("exit code = " + p.exitValue());
} catch (Exception e) {
e.printStackTrace();
}
}
try {
String[] command = {"kill", "-9", "`ps -ef | grep '程序名' | awk '{print $2}'`"};
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
System.out.println("exit code = " + p.exitValue());
} catch (Exception e) {
e.printStackTrace();
}
}
这段代码在Solaris10上面执行的结果是exit code = 1,希望被kill的程序也没kill成功。可是如果我在console里面直接执行:
kill -9 `ps -ef | grep '程序名' | awk '{print $2}'`
那么程序可以很正常地kill掉。搞不明白到底是什么导致这种差异的产生。从Java的文档里也看不出什么东西来:
public Process exec(String[] cmdarray) throws IOException
- Executes the specified command and arguments in a separate process.
This is a convenience method. An invocation of the form exec(cmdarray) behaves in exactly the same way as the invocation
exec(cmdarray, null, null). - Parameters:
cmdarray- array containing the command to call and its arguments.- Returns:
- A new
Processobject for managing the subprocess - Throws:
SecurityException- If a security manager exists and itscheckExecmethod doesn't allow creation of the subprocessIOException- If an I/O error occursNullPointerException- Ifcmdarrayisnull, or one of the elements ofcmdarrayisnullIndexOutOfBoundsException- Ifcmdarrayis an empty array (has length0)- See Also:
ProcessBuilder
如果有谁知道原因,麻烦告知一声,非常感谢。
浙公网安备 33010602011771号