tags:

views:

2945

answers:

4

Is it possible to do a "C like" fork in java, using an new independent jvm process ?

How?

+3  A: 

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

Nothing stopping you firing another JVM from here.

Paul Whelan
This isn't quite the same as fork(), since you don't get access to the copy of the existing process. All you can really do is the equivalent of fork() + exec().
Mark Bessey
fork() is **very** different from exec()
Vladimir Dyuzhev
+3  A: 

You can, as Paul explained, but note that invoking new JVM is extremely heavyweight process. You'd be much better by using threads.

Dev er dev
+3  A: 

Funnily, I am just working on this: a Java process running other Java processes. I used the article From Runtime.exec() to ProcessBuilder as a solid base, and When Runtime.exec() won't as a good advice how to gobble the output streams.

PS.: For those wondering, I had to do that (instead of spawning new threads) because yet another Java process is checking the presence of these processes which are, normally, ran separately with shell commands.

PhiLho
+2  A: 

Maybe you could go into greater detail about what you're trying to accomplish? As mentioned, you can exec() another process, which could be another instance of the JVM, but that doesn't give you the same state-sharing as fork() does in C. On the other hand, you can run threads, but there you get more sharing than you would with fork().

Mark Bessey
I simply want to avoid the sharing that thread implies. Thks for your concern :)
sakana