Arjun Sreedharan
Arjun Sreedharan

Reputation: 11453

Create a childprocess and make it run a function or class method

I come from a very C background and am totally new to Java. What I want to do is something like fork() in C. I have looked at ProcessBuilder, but all examples seem to spawn an external process as in the following example:

Process p = new ProcessBuilder("/bin/chmod", "777", path).start();
p.waitFor();

I want the new child process to start executing a new function, or a class method.

What I want to do should behave something like:

Process p = new ProcessBuilder(<CLASS_METHOD>).start();
p.waitFor();

The parent process executes the next line (the line containing waitFor()) where as the child process begins executing the given <CLASS_METHOD>.

How can I get this done?

Additional question: Is there any way I can get a handler to SIGCHLD? I want to create a new child-process when one of the child processes die.

Upvotes: 0

Views: 3924

Answers (1)

Anand J
Anand J

Reputation: 18

Why can't you just create a new java process using the process builder? Something like following.

Process p = new ProcessBuilder("/bin/java /tmp/Main.class").start();
p.waitFor();

if you don't want to hard code the class path, you can do the following to get the path.

String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();

Upvotes: 1

Related Questions