This section provides a tutorial example on how to execute system commands as separate processes outside the JVM instance.
The JVM instance also allows you to execute a system command as a separate process
by using the exec() method. The separate process can be managed these methods:
getOutputStream() - Returns an output stream representing the standard input to the process.
getInputStream() - Returns an input stream representing the standard output from the process.
waitFor() - Puts the current thread on hold until the process is terminated.
Here is tutorial example program testing exec() method:
/**
* RuntimeExec.java
* Copyright (c) 2010 by Dr. Herong Yang, herongyang.com
*/
import java.io.*;
class RuntimeExec {
public static void main(String[] a) {
PrintStream out = System.out;
Runtime rt = Runtime.getRuntime();
try {
out.println("Executing a command in a separate process...");
Process proc = rt.exec("perl HelloSleep.pl");
OutputStream procIn = proc.getOutputStream();
procIn.write("Herong".getBytes());
procIn.close();
InputStream procOut = proc.getInputStream();
byte[] msgOut = new byte[64];
int len = procOut.read(msgOut);
procOut.close();
out.println("Output from the command: "
+new String(msgOut,0,len));
out.println("Waiting for the process to finish...");
int rc = proc.waitFor();
out.println("Status code returned by the process "+rc);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The Perl program, HelloSleep.pl, is simple, reading 6 characters from the standard input,
writing a hello message to the standard output, then sleep forever:
#
#- HelloSleep.pl
#- Copyright (c) 2010 by Dr. Herong Yang, herongyang.com
#
$len = read STDIN, $msgIn, 6;
print STDOUT "Hello $msgIn!";
close STDOUT;
sleep;
When executed on my Windows XP system with JDK 1.6.0,
I got this result:
C:\herong\jvm>java RuntimeExec
Executing a command in a separate process...
Output from the command: Hello Herong!
Waiting for the process to finish...
(terminate the Perl process using Windows Task Manager)
Status code returned by the process 1
The test result confirms that the process invoked by the exec() method is running outside
the JVM instance.