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开发者_JS百科, 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
The C++ EXE is almost certainly marked as a console app. I'm thinking a jar would be considered a GUI app by default, and would do the standard detach-from-the-main-process thing.
If you were to take the C++ code and turn it into a GUI app, i think you'd see it behave similarly to the jar.
精彩评论