【发布时间】:2016-06-16 11:09:59
【问题描述】:
ProcessBuilder 不支持 bash 重定向,所以如果我运行以下命令:
import java.lang.ProcessBuilder.Redirect;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String args[]) {
ProcessBuilder builder = new ProcessBuilder();
String command = "ping 127.0.0.1 > console.log";
builder.command("bash" , "-c", command);
//builder.redirectOutput(Redirect.appendTo(new File ("console.log")));
System.out.println("Builder: " + builder.command().toString());
try {
Process p = builder.start();
System.out.println("Sleeping for 20 seconds");
Thread.sleep(20000);
p.destroy();
} catch (Exception e) {
System.out.println("An error happened here");
}
}
}
p.destroy() 只杀死父 bash -c 进程而不是子进程。有什么办法也可以杀死孩子吗? ping 将在销毁后继续运行。
根据这篇帖子Java - Process.destroy() source code for Linux,它最终会在本机c代码级别调用kill down。
但即使我在 Linux 中这样做也行不通:
[john@dub-001948-VM01:~/tmp ]$ bash -c 'ping 127.0.0.1 > console.log' &
[1] 30914
[john@dub-001948-VM01:~/tmp ]$ ps
PID TTY TIME CMD
30536 pts/1 00:00:00 bash
30914 pts/1 00:00:00 bash
30915 pts/1 00:00:00 ping
30916 pts/1 00:00:00 ps
[john@dub-001948-VM01:~/tmp ]$ kill -9 30914
[john@dub-001948-VM01:~/tmp ]$ ps -ef | grep ping
john 30915 1 0 15:19 pts/1 00:00:00 ping 127.0.0.1
john 30919 30536 0 15:19 pts/1 00:00:00 grep ping
[1]+ Killed bash -c 'ping 127.0.0.1 > console.log'
[john@dub-001948-VM01:~/tmp ]$
ping 仍在运行..
【问题讨论】:
标签: java linux bash ksh processbuilder