Why two subprocesses created by Java behave differently?

Posted by Lily on Stack Overflow See other posts from Stack Overflow or by Lily
Published on 2010-04-20T20:33:32Z Indexed on 2010/04/20 20:53 UTC
Read the original article Hit count: 293

Filed under:
|
|
|
|

I use Java Runtime.getRuntime().exec(command) to create a subprocess and print its pid as follows:

public static void main(String[] args) {

Process p2;
try {       
    p2 = Runtime.getRuntime().exec(cmd);
    Field f2 = p2.getClass().getDeclaredField("pid");
    f2.setAccessible(true);
    System.out.println( f2.get( p2 ) );
} catch (Exception ie)
{
    System.out.println("Yikes, you are not supposed to be here");
}

}

I tried both C++ executable and Java executable (.jar file). Both executables will continuously print out "Hello World" to stdout.

When cmd is the C++ executable, the pid is printed out to console but the subprocess gets killed as soon as main() returns. However, when I call the .jar executable in cmd, the subprocess does not get killed, which is the desired behavior.

I don't understand why same Java code, with different executables can behave so differently. How should I modify my code so that I could have persistent subprocesses in Java.

Newbie in this field. Any suggestion is welcomed.

Lily

© Stack Overflow or respective owner

Related posts about java

Related posts about subprocess