THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
Runs the command in cmdArray on the current system. Returns a
Process object (described below) to represent it. The string in
cmdArray[0] is the name of the command, and any subsequent strings in
the array are passed to the command as arguments.

public Processexec(String command)tHRows IOException

Equivalent to the array form of exec with the string command split into an
array wherever whitespace occurs, using a default StringTokenizer (see
page 651).

The newly created process is called a child process. By analogy, the creating process is a parent process.


Creating processes is a privileged operation and a SecurityException is thrown if you are not permitted
to do it. If anything goes wrong when the system tries to create the process, an IOException is thrown.


23.2.1. Process


The exec methods return a Process object for each child process created. This object represents the child
process in two ways. First, it provides methods to get input, output, and error streams for the child process:[1]


[1] For historical reasons these are byte stream objects instead of character streams. You can
use InputStreamReader and OutputStreamWriter to convert the bytes to
characters under the system default encoding or another of your choosing.

public abstract OutputStreamgetOutputStream()

Returns an OutputStream connected to the standard input of the child
process. Data written on this stream is read by the child process as its input.

public abstract InputStreamgetInputStream()

Returns an InputStream connected to the standard output of the child
process. When the child writes data on its output, it can be read from this
stream.

public abstract InputStreamgetErrorStream()

Returns an InputStream connected to the error output stream of the child
process. When the child writes data on its error output, it can be read from
this stream.

Here, for example, is a method that connects the standard streams of the parent process to the standard streams
of the child process so that whatever the user types will go to the specified program and whatever the program
produces will be seen by the user:


public static Process userProg(String cmd)
throws IOException
{
Process proc = Runtime.getRuntime().exec(cmd);
plugTogether(System.in, proc.getOutputStream());
plugTogether(System.out, proc.getInputStream());
plugTogether(System.err, proc.getErrorStream());
return proc;
}

Free download pdf