views:

96

answers:

1

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

+2  A: 

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.

cHao
That's not quite the answer the OP is expecting, I assume. How do you easily "take the C++ code and turn it into a GUI app"?
recipriversexclusion
Easy answer? You don't. Console and Windows subsystems are separate, and used differently. A Windows app isn't going to get a console, so unless you're attaching to the process, you'll never see the output.
cHao
Not-so-easy answer: http://msdn.microsoft.com/en-us/library/ms682055(v=VS.85).aspx
cHao
@cHao, thanks for your reply. But the thing is: I don't care the console output. As long as the subprocess is still running after the main() returns, I am already happy~
Lily