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?
PS: I am using Ubuntu 9.10 and OpenJDK-1.6. (Not sure if they matters~)
Newbie in this field. Any suggestion is welcomed.
Lily