我不确定它是否有效,但您可以尝试Process.destroy()。像这样的东西:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "\"start;" + command + "\"");
Process p = pb.start();
//...
p.destroy();
另外,不要写空的 catch 块:
} catch (IOException e) {
}
因为如果抛出异常,将很难注意到。当然,除非您知道可以忽略该异常。
更新:
linux 操作系统的概念证明:
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("ping","localhost");
pb.redirectErrorStream(true);
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
int ch,count = 0;
StringBuffer sb = new StringBuffer();
while((ch =isr.read()) > -1) {
sb.append((char)ch);
if ((char)ch == '\n') {
System.out.println( sb.toString());
sb = new StringBuffer();
}
if (count++ == 2) {
System.out.println("destroying process");
p.destroy();
}
}
}
输出:
destroying process
PING localhost (127.0.0.1) 56(84) bytes of data.
Exception in thread "main" java.io.IOException: Stream closed
64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.031 ms
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:145)
at java.io.BufferedInputStream.read(BufferedInputStream.java:308)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at sun.nio.cs.StreamDecoder.read0(StreamDecoder.java:107)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:93)
at java.io.InputStreamReader.read(InputStreamReader.java:151)
at com.infobip.rhino.Killer.main(Killer.java:24)
Java Result: 1
因为错误流被重定向到输出流,所以这些行搞砸了