导航

Runtime.exec()的问题?

Posted on 2011-03-16 12:26  teasp  阅读(1012)  评论(1)    收藏  举报

最近写的一个程序要在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();
  }
}

这段代码在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 Process object for managing the subprocess
Throws:
SecurityException - If a security manager exists and its checkExec method doesn't allow creation of the subprocess
IOException - If an I/O error occurs
NullPointerException - If cmdarray is null, or one of the elements of cmdarray is null
IndexOutOfBoundsException - If cmdarray is an empty array (has length 0)
See Also:
ProcessBuilder

如果有谁知道原因,麻烦告知一声,非常感谢。