如何在Java中终止由进程启动的子进程?

3
在下面的代码片段中,如果我仅使用p.destroy()销毁Process p,则只有进程p(即cmd.exe)会被关闭。但是其子进程iperf.exe没有被终止。如何在Java中终止此进程。
Process p= Runtime.getRuntime().exec("cmd /c iperf -s > testresult.txt");

1
不要使用 Runtime.exec(),请使用 ProcessBuilder - fge
1
让主进程等待子进程: p.waitFor(); p.destroy(); 然后终止所有。 - mmoghrabi
3个回答

3
在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()将按您要求工作。

1
您应该使用这段代码而不是原来的代码:

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)。如何做到这一点?有什么想法吗? - shriguru nayak
1
只需要 p.destroy()。我已经将 cmd.exe 和 iperf 分开,所以在 p.destroy() 时会杀死 iperf。 - tbodt

-1
您可以参考以下代码片段:
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。只有在JVM正常关闭时,此代码才会清除生成的进程。 - zloster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接