在下面的代码片段中,如果我使用p.destroy()
销毁Process p
,只有进程p
(即cmd.exe
)正在被破坏。但不是它的小孩iperf.exe
。如何用Java终止这个过程。如何杀死java中的进程启动的子进程?
Process p= Runtime.getRuntime().exec("cmd /c iperf -s > testresult.txt");
在下面的代码片段中,如果我使用p.destroy()
销毁Process p
,只有进程p
(即cmd.exe
)正在被破坏。但不是它的小孩iperf.exe
。如何用Java终止这个过程。如何杀死java中的进程启动的子进程?
Process p= Runtime.getRuntime().exec("cmd /c iperf -s > testresult.txt");
在Java 7中ProcessBuilder可以为你做重定向,所以只需直接运行iperf而不是通过cmd.exe
。
ProcessBuilder pb = new ProcessBuilder("iperf", "-s");
pb.redirectOutput(new File("testresult.txt"));
Process p = pb.start();
产生的p
现在是iText的本身,所以destroy()
根据您的需要将工作。
您应使用此代码来代替:
Process p= Runtime.getRuntime().exec("iperf -s");
InputStream in = p.getInputStream();
FileOutputStream out = new FileOutputStream("testresult.txt");
byte[] bytes;
in.read(bytes);
out.write(bytes);
这段代码也不会精确地工作,但你只需要一点点的流拨弄。
但我需要销毁子进程(iperf)。怎么做?任何想法? –
只要'p.destroy()'。我分离了cmd.exe和iperf,所以iperf会在'p.destroy()'中被杀死。 – tbodt
你可以参考下面的代码片段:
public class Test {
public static void main(String args[]) throws Exception {
final Process process = Runtime.getRuntime().exec("notepad.exe");
//if killed abnormally (For Example using ^C from cmd)
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
process.destroy();
System.out.println(" notepad killed ");
}
});
}
}
这个答案是**不正确。请检查'Runtime'类的[javadoc](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#addShutdownHook-java.lang.Thread-)。只有在JVM正常关闭时,此代码才会清理生成的进程。 – zloster
不要使用'的Runtime.exec()',用'ProcessBuilder' – fge
让主进程等待子进程 p.waitFor() ; p.destroy(); 然后终止所有 – user1283633