【问题标题】:Process.destroy() is not killing children of ProcessProcess.destroy() 不会杀死 Process 的子进程
【发布时间】: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


    【解决方案1】:

    看起来bash 做了一个 fork 和 exec 来启动子进程,所以子进程不会被杀死。但是,如果您使用 ksh 而不是 bash,您将获得一个没有 exec 的 fork:

    ksh -c ping 127.0.0.1 > console.log

    使用ksh、process.destroy() 会杀死 ksh 和子进程

    不过我不确定,ksh 和 bash 手册页中的 -c 选项看起来非常相似。

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 1970-01-01
      • 2016-01-24
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多