2016-06-16 11 views
0

Process nicht unterstützt bash umleitet, so dass, wenn ich folgendes ausgeführt:Process.destroy() nicht Kinder von Prozess Tötung

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() tötet nur die übergeordnete bash -c Prozess, aber nicht das Kind. Gibt es eine Möglichkeit, das Kind auch zu töten? Ping wird nach der Zerstörung weiter ausgeführt.

Nach diesem Beitrag Java - Process.destroy() source code for Linux, ruft es schließlich kill down auf der nativen c-Code-Ebene.

Aber auch wenn ich dies tun in Linux funktioniert es nicht:

[[email protected]:~/tmp ]$ bash -c 'ping 127.0.0.1 > console.log' & 
[1] 30914 
[[email protected]:~/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 
[[email protected]:~/tmp ]$ kill -9 30914 
[[email protected]:~/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' 
[[email protected]:~/tmp ]$ 

Ping läuft noch ..

Antwort

1

Es sieht aus wie bash ist ein fork und exec das Kind zu starten, damit das Kind nicht getötet wird. Wenn Sie jedoch verwenden ksh statt bash, werden Sie eine Gabel ohne exec erhalten:

ksh -c ping 127.0.0.1 > console.log

Mit dem ksh, process.destroy() kills sowohl die KSH und das Kind Prozess

ich nicht weiß Sicherlich sieht die -c Option in der Manpage für beide ksh und bash ziemlich ähnlich aus.