Reputation: 310
In the below code snippet, if I destroy Process p
using p.destroy()
only process p
(i.e.cmd.exe
) is getting destroyed. But not its child iperf.exe
. How to terminate this process in Java.
Process p= Runtime.getRuntime().exec("cmd /c iperf -s > testresult.txt");
Upvotes: 3
Views: 5772
Reputation: 1
You can refer following code snippet:
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 ");
}
});
}
}
Upvotes: -1
Reputation: 122424
In Java 7 ProcessBuilder can do the redirection for you, so just run iperf directly rather than through cmd.exe
.
ProcessBuilder pb = new ProcessBuilder("iperf", "-s");
pb.redirectOutput(new File("testresult.txt"));
Process p = pb.start();
The resulting p
is now itext itself, so destroy()
will work as you require.
Upvotes: 3
Reputation: 17017
You should use this code instead:
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);
This code will not work exactly, but you just need to fiddle with the streams a little.
Upvotes: 1