Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Advanced
Jan 20, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Spawning New Processes From a Java Program

The Java Runtime Environment (JRE) shields Java developers from the system level burdens of starting and stopping processes. A Java application runs inside the JVM, while a Java applet runs in a Web browser. In effect, both run inside the JVM (since the browser runs the applet in its own JVM). A standard Java application handles parallel tasks by running these tasks in independent threads.

However, most systems that support a Java runtime environment are capable of running several processes simultaneously. Java applications also are able to start new system programs calling the exec() method of the Runtime class. The exec() method has four forms:

1. public Process exec(String cmd) throws IOException
2. public Process exec(String[] cmds) throws IOException
3. public Process exec(String cmd, String[] env) throws IOException
4. public Process exec(String[] cmds, String[] env) throws IOException
The cmd parameter in Line 1 specifies the process to run. In Line 2, an array of String variables, cmds, is passed to the exec() method. The first String (cmd[0]) is the program name and the rest of the array strings are the arguments to the program. Lines 3 and 4 extend the methods in Lines 1 and 2 by allowing the Java program to supply environment variables in the array env.

Note that the exec() method results in the creation of a new child process. This process is a system process managed by the platform's operating system that runs outside the JVM. The following example uses the exec() call shown on Line 4:

1. Runtime rt = Runtime.getRuntime();
2. String[] cmds = { "/bin/ls", "/" };
3. String[] env = { "TERM=VT100" };
4. Process p1 = rt.exec(cmds, env);
This code is equivalent to running the shell commands:
$ set TERM=VT100
$ /bin/ls /
Ajit Sagar
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date