Process provides control of native processes started by
ProcessBuilder.start and Runtime.exec.
The class provides methods for performing input from the process, performing
output to the process, waiting for the process to complete,
checking the exit status of the process, and destroying (killing)
the process.
The ProcessBuilder#start() and
Runtime.exec
methods create a native process and return an instance of a
subclass of Process that can be used to control the process
and obtain information about it.
The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts.
By default, the created process does not have its own terminal
or console. All its standard I/O (i.e. stdin, stdout, stderr)
operations will be redirected to the parent process, where they can
be accessed via the streams obtained using the methods
getOutputStream(),
getInputStream(), and
getErrorStream().
The I/O streams of characters and lines can be written and read using the methods
outputWriter(), outputWriter(Charset),
inputReader(), inputReader(Charset),
errorReader(), and errorReader(Charset).
The parent process uses these streams to feed input to and get output
from the process. Because some native platforms only provide
limited buffer size for standard input and output streams, failure
to promptly write the input stream or read the output stream of
the process may cause the process to block, or even deadlock.
Where desired,
process I/O can also be redirected
using methods of the ProcessBuilder class.
There is no requirement that the process represented by a Process object execute asynchronously or concurrently with respect
to the Java process that owns the Process object.
As of 1.5, ProcessBuilder#start() is the preferred way
to create a Process.
Subclasses of Process should ensure that each overridden method
invokes the superclass method.
For example, if close is overridden, the subclass should
ensure that Process.close() is called.
public class LoggingProcess extends java.lang.Process { ... @Override public void close() throws IOException { try { super.close(); } catch (IOException ex) { LOGGER.log(ex); } finally { LOGGER.log("process closed"); } } ... }
Subclasses of Process that wrap another Process instance
should override and delegate the onExit() and
toHandle() methods to provide a fully functional Process including the
process id,
information about the process,
direct children, and
direct children plus descendants of those children of the process.
Delegating to the underlying Process or ProcessHandle is typically
easiest and most efficient.
The process is not killed when there are no more references to the Process object,
but rather the process continues executing asynchronously.
The process implementation closes file descriptors and handles for streams
that are no longer referenced to prevent leaking operating system resources.
Processes that have terminated or been terminated are monitored and their resources released.
Streams should be closed when they are no longer needed, to avoid delaying
releasing the operating system resources.
Try-with-resources can be used to open and close the streams.
For example, to capture the output of a program known to produce some output and then exit:
List<String> capture(List<String> args) throws Exception { ProcessBuilder pb = new ProcessBuilder(args); try (Process process = pb.start(); BufferedReader in = process.inputReader()) { List<String> captured = in.readAllLines(); int status = process.waitFor(); if (status != 0) { throw new RuntimeException("Process %d: %s failed with %d" .formatted(process.pid(), args, status)); } return captured; } }
Stream resources (file descriptor or handle) are always paired; one in the invoking process and the other end of that connection in the invoked process. Closing a stream at either end terminates communication but does not have any direct effect on the other Process. The closing of the stream typically results in the other process exiting.
Destroying a process signals the operating system to terminate the process. It is up to the operating system to clean up and release the resources of that process. Typically, file descriptors and handles are closed. When they are closed, any connections to other processes are terminated and file descriptors and handles in the invoking process signal end-of-file or closed. Usually, that is seen as an end-of-file or an exception.
| Modifier and Type | Class and Description |
|---|---|
| private static class | Process.
A nested class to delay looking up the Charset for the native encoding. |
| pack-priv static class | Process.
An input stream for a subprocess pipe that skips by reading bytes instead of seeking, the underlying pipe does not support seek. |
| pack-priv static class | Process.
An output stream for a subprocess pipe. |
| Modifier and Type | Field and Description |
|---|---|
| private boolean | |
| private Charset | |
| private BufferedReader | |
| private Charset | |
| private BufferedReader | |
| private Charset | |
| private BufferedWriter |
| Access | Constructor and Description |
|---|---|
| public |
| Modifier and Type | Method and Description |
|---|---|
| public Stream | Returns: a sequential Stream of ProcessHandles for processes that are direct children of the processReturns a snapshot of the direct children of the process. |
| public void | close()
Implements java. Closes all reader and writer streams and waits for the process to terminate. |
| public Stream | Returns: a sequential Stream of ProcessHandles for processes that are descendants of the processReturns a snapshot of the descendants of the process. |
| public abstract void | |
| public Process | Returns: theProcess object representing the
process forcibly destroyedKills the process forcibly. |
| public final BufferedReader | Returns: aBufferedReader using the
native.encoding if supported, otherwise, the
Charset#defaultCharset()Returns a |
| public final BufferedReader | Returns: aBufferedReader for the standard error of the process using the charsetthe charset)Charset used to decode bytes to charactersReturns a |
| public abstract int | Returns: the exit value of the process represented by thisProcess object. By convention, the value
0 indicates normal termination.Returns the exit value for the process. |
| public abstract InputStream | Returns: the input stream connected to the error output of the processReturns the input stream connected to the error output of the process. |
| public abstract InputStream | Returns: the input stream connected to the normal output of the processReturns the input stream connected to the normal output of the process. |
| public abstract OutputStream | Returns: the output stream connected to the normal input of the processReturns the output stream connected to the normal input of the process. |
| private boolean | hasExited()
This is called from the default implementation of
|
| public ProcessHandle. | Returns: a snapshot of information about the process, always non-nullReturns a snapshot of information about the process. |
| public final BufferedReader | Returns: aBufferedReader using the
native.encoding if supported, otherwise, the
Charset#defaultCharset()Returns a |
| public final BufferedReader | Returns: aBufferedReader for the standard output of the process using the charsetthe charset)Charset used to decode bytes to charactersReturns a |
| public boolean | Returns: true if the process represented by this
Process object has not yet terminated.Tests whether the process represented by this |
| public CompletableFuture | Returns: a newCompletableFuture<Process> for the ProcessReturns a |
| public final BufferedWriter | Returns: aBufferedWriter to the standard input of the process using the charset
for the native.encoding system propertyReturns a |
| public final BufferedWriter | Returns: aBufferedWriter to the standard input of the process using the charsetthe charset)Charset to encode characters to bytesReturns a |
| public long | |
| private static IOException | |
| public boolean | supportsNormalTermination()
Returns |
| public ProcessHandle | |
| private boolean | |
| public abstract int | Returns: the exit value of the process represented by thisProcess object. By convention, the value
0 indicates normal termination.Causes the current thread to wait, if necessary, until the
process represented by this |
| public boolean | Returns: true if the process has exited and false if
the waiting time elapsed before the process has exited.the maximum time to wait timeout, TimeUnit the time unit of the unit)timeout argumentCauses the current thread to wait, if necessary, until the
process represented by this |
| public boolean | Returns: true if the process has exited and false if
the waiting duration elapsed before the process has exited.the maximum duration to wait; if not positive,
this method returns immediately. duration)Causes the current thread to wait, if necessary, until the
process represented by this |
| private Process |
| closed | back to summary |
|---|---|
| private boolean closed | |
| errorCharset | back to summary |
|---|---|
| private Charset errorCharset | |
| errorReader | back to summary |
|---|---|
| private BufferedReader errorReader | |
| inputCharset | back to summary |
|---|---|
| private Charset inputCharset | |
| inputReader | back to summary |
|---|---|
| private BufferedReader inputReader | |
| outputCharset | back to summary |
|---|---|
| private Charset outputCharset | |
| outputWriter | back to summary |
|---|---|
| private BufferedWriter outputWriter | |
| Process | back to summary |
|---|---|
| public Process() Default constructor for Process. | |
| children | back to summary |
|---|---|
| public Stream Returns a snapshot of the direct children of the process. The parent of a direct child process is the process. Typically, a process that is not alive has no children. Note that processes are created and terminate asynchronously. There is no guarantee that a process is alive. Implementation Specification This implementation returns the direct children as:
| |
| close | back to summary |
|---|---|
| public void close() throws IOException Implements java. Closes all reader and writer streams and waits for the process to terminate.
This method is idempotent, if this If the data from the process input or error streams is needed, it must be read before calling this method. The contents of streams that have not been read to end of stream are lost, they are discarded or ignored. If the process exit value is of interest, then the caller must wait for the process to terminate before calling this method.
Streams should be closed when no longer needed.
Closing an already closed stream usually has no effect but is specific to the stream.
If an
After the streams are closed this method waits for the
process to terminate. If interrupted while waiting
the process is forcibly destroyed and
this method continues to wait for the process to terminate.
The interrupted status is re-asserted before this method returns or
any API Note Try-with-resources example to write text to a process, read back the response, and close the streams and process: void main() { try (Process p = new ProcessBuilder("cat").start(); var writer = p.outputWriter(); var reader = p.inputReader()) { writer.write(haiku); writer.close(); // Read all lines and print each reader.readAllLines() .forEach(IO::println); var status = p.waitFor(); if (status != 0) throw new RuntimeException("unexpected process status: " + status); } catch (Exception e) { System.out.println("Process failed: " + e); } } static final String haiku = """ Oh, the sunrise glow; Paddling with the river flow; Chilling still, go slow. """; Implementation Note Concrete implementations that override this class are strongly encouraged to
override this method and invoke the superclass Implementation Specification This method closes the process I/O streams and then
waits for the process to terminate.
If
| |
| descendants | back to summary |
|---|---|
| public Stream Returns a snapshot of the descendants of the process. The descendants of a process are the children of the process plus the descendants of those children, recursively. Typically, a process that is not alive has no children. Note that processes are created and terminate asynchronously. There is no guarantee that a process is alive. Implementation Specification This implementation returns all children as:
| |
| destroy | back to summary |
|---|---|
| public abstract void destroy() Kills the process.
Whether the process represented by this
The | |
| destroyForcibly | back to summary |
|---|---|
| public Process destroyForcibly() Kills the process forcibly. The process represented by this
The
Invoking this method on Implementation Specification The default implementation of this method invokes Implementation Note Concrete implementations of this class are strongly encouraged to override this method with a compliant implementation. API Note The process may not terminate immediately.
i.e.
| |
| errorReader | back to summary |
|---|---|
| public final BufferedReader errorReader() Returns a This method delegates to The error reader should be closed when it is no longer needed. API Note Use either this method or the error stream
but not both on the same
| |
| errorReader | back to summary |
|---|---|
| public final BufferedReader errorReader(Charset charset) Returns a Characters are read by an InputStreamReader that reads and decodes bytes
from this process The first call to this method creates the If the standard error of the process has been redirected using
The error reader should be closed when it is no longer needed. API Note Use either this method or the error stream
but not both on the same When the process has terminated, and the standard error has not been redirected, reading of the bytes available from the underlying stream is on a best effort basis and may be unpredictable.
| |
| exitValue | back to summary |
|---|---|
| public abstract int exitValue() Returns the exit value for the process.
| |
| getErrorStream | back to summary |
|---|---|
| public abstract InputStream getErrorStream() Returns the input stream connected to the error output of the
process. The stream obtains data piped from the error output
of the process represented by this If the standard error of the process has been redirected using
The error stream should be closed when it is no longer needed. API Note Use either this method or an error reader
but not both on the same Implementation Note Implementation note: It is a good idea for the returned input stream to be buffered.
| |
| getInputStream | back to summary |
|---|---|
| public abstract InputStream getInputStream() Returns the input stream connected to the normal output of the
process. The stream obtains data piped from the standard
output of the process represented by this If the standard output of the process has been redirected using
Otherwise, if the standard error of the process has been
redirected using
The input stream should be closed when it is no longer needed. API Note Use either this method or an input reader
but not both on the same Implementation Note Implementation note: It is a good idea for the returned input stream to be buffered.
| |
| getOutputStream | back to summary |
|---|---|
| public abstract OutputStream getOutputStream() Returns the output stream connected to the normal input of the
process. Output to the stream is piped into the standard
input of the process represented by this If the standard input of the process has been redirected using
The output stream should be closed when it is no longer needed. API Note When writing to both Implementation Note Implementation note: It is a good idea for the returned output stream to be buffered.
| |
| hasExited | back to summary |
|---|---|
| private boolean hasExited() This is called from the default implementation of
| |
| info | back to summary |
|---|---|
| public ProcessHandle. Returns a snapshot of information about the process. A Implementation Specification This implementation returns information about the process as:
| |
| inputReader | back to summary |
|---|---|
| public final BufferedReader inputReader() Returns a This method delegates to The reader should be closed when it is no longer needed. API Note Use either this method or the input stream
but not both on the same
| |
| inputReader | back to summary |
|---|---|
| public final BufferedReader inputReader(Charset charset) Returns a Characters are read by an InputStreamReader that reads and decodes bytes
from this process The first call to this method creates the If the standard output of the process has been redirected using
The reader should be closed when it is no longer needed. Otherwise, if the standard error of the process has been redirected using
API Note Use either this method or the input stream
but not both on the same When the process has terminated, and the standard input has not been redirected, reading of the bytes available from the underlying stream is on a best effort basis and may be unpredictable.
| |
| isAlive | back to summary |
|---|---|
| public boolean isAlive() Tests whether the process represented by this
| |
| onExit | back to summary |
|---|---|
| public CompletableFuture Returns a
Calling
Processes returned from API Note Using Process p = new ProcessBuilder("cmp", "f1", "f2").start(); Future<Boolean> identical = p.onExit().thenApply(p1 -> p1.exitValue() == 0); ... if (identical.get()) { ... } Implementation Specification This implementation executes
When External implementations should override this method and provide a more efficient implementation. For example, to delegate to the underlying process, it can do the following: public CompletableFuture<Process> onExit() { return delegate.onExit().thenApply(p -> this); } API Note The process may be observed to have terminated with
| |
| outputWriter | back to summary |
|---|---|
| public final BufferedWriter outputWriter() Returns a This method delegates to The output writer should be closed when it is no longer needed.
| |
| outputWriter | back to summary |
|---|---|
| public final BufferedWriter outputWriter(Charset charset) Returns a Characters written by the writer are encoded to bytes using The first call to this method creates the If the standard input of the process has been redirected using
The output writer should be closed when it is no longer needed. API Note A BufferedWriter writes characters, arrays of characters, and strings.
Wrapping the
When writing to both
| |
| pid | back to summary |
|---|---|
| public long pid() Returns the native process ID of the process. The native process ID is an identification number that the operating system assigns to the process. Implementation Specification The implementation of this method returns the process id as:
| |
| quietClose | back to summary |
|---|---|
| private static IOException quietClose(Closeable c, IOException firstIOE) | |
| supportsNormalTermination | back to summary |
|---|---|
| public boolean supportsNormalTermination() Returns
Invoking this method on Implementation Specification This implementation throws an instance of
| |
| toHandle | back to summary |
|---|---|
| public ProcessHandle toHandle() Returns a ProcessHandle for the Process.
Implementation Specification This implementation throws an instance of
| |
| tryWait | back to summary |
|---|---|
| private boolean tryWait() | |
| waitFor | back to summary |
|---|---|
| public abstract int waitFor() throws InterruptedException Causes the current thread to wait, if necessary, until the
process represented by this
| |
| waitFor | back to summary |
|---|---|
| public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException Causes the current thread to wait, if necessary, until the
process represented by this If the process has already terminated then this method returns
immediately with the value Implementation Specification The default implementation of this method polls the Implementation Note Concrete implementations of this class are strongly encouraged to override this method with a more efficient implementation.
| |
| waitFor | back to summary |
|---|---|
| public boolean waitFor(Duration duration) throws InterruptedException Causes the current thread to wait, if necessary, until the
process represented by this If the process has already terminated then this method returns
immediately with the value Implementation Specification The default implementation of this method polls the Implementation Note Concrete implementations of this class are strongly encouraged to override this method with a more efficient implementation.
| |
| waitForInternal | back to summary |
|---|---|
| private Process waitForInternal() Wait for the process to exit by calling
| |
| Modifier and Type | Field and Description |
|---|---|
| private static final Charset |
| Access | Constructor and Description |
|---|---|
| private |
| Modifier and Type | Method and Description |
|---|---|
| pack-priv static Charset |
| nativeCharset | back to summary |
|---|---|
| private static final Charset nativeCharset | |
| CharsetHolder | back to summary |
|---|---|
| private CharsetHolder() | |
| nativeCharset | back to summary |
|---|---|
| pack-priv static Charset nativeCharset() Charset for the native encoding or {@link Charset#defaultCharset(). | |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| public int | |
| public int | read(byte[] b)
Overrides java. Reads up to |
| public int | read(byte[] b, int off, int len)
Overrides java. Reads up to |
| public long | skip(long n)
Overrides java. Skips over and discards |
| PipeInputStream | back to summary |
|---|---|
| pack-priv PipeInputStream(FileDescriptor fd) | |
| read | back to summary |
|---|---|
| public int read() throws IOException Overrides java. Doc from java. Reads a byte of data from this input stream. This method blocks if no input is yet available.
| |
| read | back to summary |
|---|---|
| public int read(byte[] b) throws IOException Overrides java. Doc from java. Reads up to
| |
| read | back to summary |
|---|---|
| public int read(byte[] b, int off, int len) throws IOException Overrides java. Doc from java. Reads up to
| |
| skip | back to summary |
|---|---|
| public long skip(long n) throws IOException Overrides java. Doc from java. Skips over and discards The This method may skip more bytes than what are remaining in the backing file. This produces no exception and the number of bytes skipped may include some number of bytes that were beyond the EOF of the backing file. Attempting to read from the stream after skipping past the end will result in -1 indicating the end of the file.
| |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| public void | write(int b)
Overrides java. Writes the specified byte to this file output stream. |
| public void | write(byte[] b)
Overrides java. Writes |
| public void | write(byte[] b, int off, int len)
Overrides java. Writes |
| PipeOutputStream | back to summary |
|---|---|
| pack-priv PipeOutputStream(FileDescriptor fd) | |
| write | back to summary |
|---|---|
| public void write(int b) throws IOException Overrides java. Doc from java. Writes the specified byte to this file output stream. Implements
the
| |
| write | back to summary |
|---|---|
| public void write(byte[] b) throws IOException Overrides java. Doc from java. Writes
| |
| write | back to summary |
|---|---|
| public void write(byte[] b, int off, int len) throws IOException Overrides java. Doc from java. Writes
| |