APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.lang

public abstract Class Process

extends Object
implements Closeable
Class Inheritance
All Implemented Interfaces
java.io.Closeable, java.lang.AutoCloseable
Known Direct Subclasses
java.lang.ProcessImpl
Imports
jdk.internal.misc.Blocker, jdk.internal.util.StaticProperty, java.io.*, java.lang.ProcessBuilder.Redirect, java.nio.charset.Charset, .UnsupportedCharsetException, java.time.Duration, java.util.Objects, java.util.concurrent.CompletableFuture, .ForkJoinPool, .TimeUnit, java.util.stream.Stream

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"); } } ... }
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.

Resource Usage

Starting a process uses resources in both the invoking process and the invoked process and for the communication streams between them. The resources to control the process and for communication between the processes are retained until there are no longer any references to the Process or the input, error, and output streams or readers, or they have been closed. The Process close method closes all the streams and terminates the process to release the resources. Using try-with-resources will ensure the process is terminated when the try-with-resources block exits.

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; } }
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.

Since
1.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
Process.CharsetHolder

A nested class to delay looking up the Charset for the native encoding.

pack-priv static class
Process.PipeInputStream

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.PipeOutputStream

An output stream for a subprocess pipe.

Field Summary

Modifier and TypeField and Description
private boolean
private Charset
private BufferedReader
private Charset
private BufferedReader
private Charset
private BufferedWriter

Constructor Summary

AccessConstructor and Description
public
Process()

Default constructor for Process.

Method Summary

Modifier and TypeMethod and Description
public Stream<ProcessHandle>

Returns:

a sequential Stream of ProcessHandles for processes that are direct children of the process
children
()

Returns a snapshot of the direct children of the process.

public void
close()

Implements java.io.Closeable.close.

Closes all reader and writer streams and waits for the process to terminate.

public Stream<ProcessHandle>

Returns:

a sequential Stream of ProcessHandles for processes that are descendants of the process
descendants
()

Returns a snapshot of the descendants of the process.

public abstract void
destroy()

Kills the process.

public Process

Returns:

the Process object representing the process forcibly destroyed
destroyForcibly
()

Kills the process forcibly.

public final BufferedReader

Returns:

a BufferedReader using the native.encoding if supported, otherwise, the Charset#defaultCharset()
errorReader
()

Returns a BufferedReader connected to the standard error of the process.

public final BufferedReader

Returns:

a BufferedReader for the standard error of the process using the charset
errorReader
(Charset
the Charset used to decode bytes to characters
charset
)

Returns a BufferedReader connected to the standard error of this process using a Charset.

public abstract int

Returns:

the exit value of the process represented by this Process object. By convention, the value 0 indicates normal termination.
exitValue
()

Returns the exit value for the process.

public abstract InputStream

Returns:

the input stream connected to the error output of the process
getErrorStream
()

Returns 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 process
getInputStream
()

Returns 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 process
getOutputStream
()

Returns the output stream connected to the normal input of the process.

private boolean
hasExited()

This is called from the default implementation of waitFor(long, TimeUnit) and waitFor(Duration), which are specified to poll exitValue().

public ProcessHandle.Info

Returns:

a snapshot of information about the process, always non-null
info
()

Returns a snapshot of information about the process.

public final BufferedReader

Returns:

a BufferedReader using the native.encoding if supported, otherwise, the Charset#defaultCharset()
inputReader
()

Returns a BufferedReader connected to the standard output of the process.

public final BufferedReader

Returns:

a BufferedReader for the standard output of the process using the charset
inputReader
(Charset
the Charset used to decode bytes to characters
charset
)

Returns a BufferedReader connected to the standard output of this process using a Charset.

public boolean

Returns:

true if the process represented by this Process object has not yet terminated.
isAlive
()

Tests whether the process represented by this Process is alive.

public CompletableFuture<Process>

Returns:

a new CompletableFuture<Process> for the Process
onExit
()

Returns a CompletableFuture<Process> for the termination of the Process.

public final BufferedWriter

Returns:

a BufferedWriter to the standard input of the process using the charset for the native.encoding system property
outputWriter
()

Returns a BufferedWriter connected to the normal input of the process using the native encoding.

public final BufferedWriter

Returns:

a BufferedWriter to the standard input of the process using the charset
outputWriter
(Charset
the Charset to encode characters to bytes
charset
)

Returns a BufferedWriter connected to the normal input of the process using a Charset.

public long

Returns:

the native process id of the process
pid
()

Returns the native process ID of the process.

private static IOException
public boolean

Returns:

true if the implementation of destroy is to normally terminate the process; otherwise, destroy forcibly terminates the process
supportsNormalTermination
()

Returns true if the implementation of destroy is to normally terminate the process, Returns false if the implementation of destroy forcibly and immediately terminates the process.

public ProcessHandle

Returns:

Returns a ProcessHandle for the Process
toHandle
()

Returns a ProcessHandle for the Process.

private boolean
public abstract int

Returns:

the exit value of the process represented by this Process object. By convention, the value 0 indicates normal termination.
waitFor
()

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

public boolean

Returns:

true if the process has exited and false if the waiting time elapsed before the process has exited.
waitFor
(long
the maximum time to wait
timeout
,
TimeUnit
the time unit of the timeout argument
unit
)

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated, or the specified waiting time elapses.

public boolean

Returns:

true if the process has exited and false if the waiting duration elapsed before the process has exited.
waitFor
(Duration
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 Process object has terminated, or the specified waiting duration elapses.

private Process

Returns:

the Process
waitForInternal
()

Wait for the process to exit by calling waitFor.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

closedback to summary
private boolean closed
errorCharsetback to summary
private Charset errorCharset
errorReaderback to summary
private BufferedReader errorReader
inputCharsetback to summary
private Charset inputCharset
inputReaderback to summary
private BufferedReader inputReader
outputCharsetback to summary
private Charset outputCharset
outputWriterback to summary
private BufferedWriter outputWriter

Constructor Detail

Processback to summary
public Process()

Default constructor for Process.

Method Detail

childrenback to summary
public Stream<ProcessHandle> children()

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: toHandle().children().

Returns:Stream<ProcessHandle>

a sequential Stream of ProcessHandles for processes that are direct children of the process

Exceptions
UnsupportedOperationException:
if the Process implementation does not support this operation
Since
9
closeback to summary
public void close() throws IOException

Implements java.io.Closeable.close.

Closes all reader and writer streams and waits for the process to terminate. This method is idempotent, if this Process has already been closed invoking this method has no effect.

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 IOException occurs when closing a stream it is thrown after the process has terminated. Exceptions thrown by closing the streams, if any, are added to the first IOException as suppressed exceptions.

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 IOExceptions are thrown.

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. """;
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 close method.

Implementation Specification

This method closes the process I/O streams and then waits for the process to terminate. If waitFor() is interrupted the process is forcibly destroyed and then close() waits for the process to terminate.

Annotations
@Override
Exceptions
IOException:
if closing any of the streams throws an exception
Since
26
descendantsback to summary
public Stream<ProcessHandle> descendants()

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: toHandle().descendants().

Returns:Stream<ProcessHandle>

a sequential Stream of ProcessHandles for processes that are descendants of the process

Exceptions
UnsupportedOperationException:
if the Process implementation does not support this operation
Since
9
destroyback to summary
public abstract void destroy()

Kills the process. Whether the process represented by this Process object is normally terminated or not is implementation dependent. Forcible process destruction is defined as the immediate termination of a process, whereas normal termination allows the process to shut down cleanly. If the process is not alive, no action is taken.

The java.util.concurrent.CompletableFuture from onExit is completed when the process has terminated.

destroyForciblyback to summary
public Process destroyForcibly()

Kills the process forcibly. The process represented by this Process object is forcibly terminated. Forcible process destruction is defined as the immediate termination of a process, whereas normal termination allows the process to shut down cleanly. If the process is not alive, no action is taken.

The java.util.concurrent.CompletableFuture from onExit is completed when the process has terminated.

Invoking this method on Process objects returned by ProcessBuilder#start() and Runtime#exec forcibly terminate the process.

Implementation Specification

The default implementation of this method invokes destroy and so may not forcibly terminate the process.

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. isAlive() may return true for a brief period after destroyForcibly() is called. This method may be chained to waitFor() if needed.

Returns:Process

the Process object representing the process forcibly destroyed

Since
1.8
errorReaderback to summary
public final BufferedReader errorReader()

Returns a BufferedReader connected to the standard error of the process. The Charset for the native encoding is used to read characters, lines, or stream lines from standard error.

This method delegates to errorReader(Charset) using the Charset named by the native.encoding system property. If the native.encoding is not a valid charset name or not supported the Charset#defaultCharset() is used.

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 Process. The error reader consumes and buffers bytes from the error stream. Bytes read from the error stream would not be seen by the reader and the buffer contents are unpredictable.

Returns:BufferedReader

a BufferedReader using the native.encoding if supported, otherwise, the Charset#defaultCharset()

Since
17
errorReaderback to summary
public final BufferedReader errorReader(Charset charset)

Returns a BufferedReader connected to the standard error of this process using a Charset. The BufferedReader can be used to read characters, lines, or stream lines of the standard error.

Characters are read by an InputStreamReader that reads and decodes bytes from this process getErrorStream(). Bytes are decoded to characters using the charset; malformed-input and unmappable-character sequences are replaced with the charset's default replacement. The BufferedReader reads and buffers characters from the InputStreamReader.

The first call to this method creates the BufferedReader, if called again with the same charset the same BufferedReader is returned. It is an error to call this method again with a different charset.

If the standard error of the process has been redirected using ProcessBuilder.redirectError or ProcessBuilder.redirectErrorStream then the InputStreamReader will be reading from a null input stream.

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 Process. The error reader consumes and buffers bytes from the error stream. Bytes read from the error stream would not be seen by the reader and the buffer contents are unpredictable.

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.

Parameters
charset:Charset

the Charset used to decode bytes to characters

Returns:BufferedReader

a BufferedReader for the standard error of the process using the charset

Exceptions
NullPointerException:
if the charset is null
IllegalStateException:
if called more than once with different charset arguments
Since
17
exitValueback to summary
public abstract int exitValue()

Returns the exit value for the process.

Returns:int

the exit value of the process represented by this Process object. By convention, the value 0 indicates normal termination.

Exceptions
IllegalThreadStateException:
if the process represented by this Process object has not yet terminated
getErrorStreamback 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 Process object.

If the standard error of the process has been redirected using ProcessBuilder.redirectError or ProcessBuilder.redirectErrorStream then this method will return a null input stream.

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 Process. The error reader consumes and buffers bytes from the error stream. Bytes read from the error stream would not be seen by the reader and the buffer contents are unpredictable.

Implementation Note

Implementation note: It is a good idea for the returned input stream to be buffered.

Returns:InputStream

the input stream connected to the error output of the process

getInputStreamback 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 Process object.

If the standard output of the process has been redirected using ProcessBuilder.redirectOutput then this method will return a null input stream.

Otherwise, if the standard error of the process has been redirected using ProcessBuilder.redirectErrorStream then the input stream returned by this method will receive the merged standard output and the standard error of the process.

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 Process. The input reader consumes and buffers bytes from the input stream. Bytes read from the input stream would not be seen by the reader and buffer contents are unpredictable.

Implementation Note

Implementation note: It is a good idea for the returned input stream to be buffered.

Returns:InputStream

the input stream connected to the normal output of the process

getOutputStreamback 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 Process object.

If the standard input of the process has been redirected using ProcessBuilder.redirectInput then this method will return a null output stream.

The output stream should be closed when it is no longer needed.

API Note

When writing to both getOutputStream() and either outputWriter() or outputWriter(Charset), BufferedWriter.flush should be called before writes to the OutputStream.

Implementation Note

Implementation note: It is a good idea for the returned output stream to be buffered.

Returns:OutputStream

the output stream connected to the normal input of the process

hasExitedback to summary
private boolean hasExited()

This is called from the default implementation of waitFor(long, TimeUnit) and waitFor(Duration), which are specified to poll exitValue().

infoback to summary
public ProcessHandle.Info info()

Returns a snapshot of information about the process.

A ProcessHandle.Info instance has accessor methods that return information about the process if it is available.

Implementation Specification

This implementation returns information about the process as: toHandle().info().

Returns:ProcessHandle.Info

a snapshot of information about the process, always non-null

Exceptions
UnsupportedOperationException:
if the Process implementation does not support this operation
Since
9
inputReaderback to summary
public final BufferedReader inputReader()

Returns a BufferedReader connected to the standard output of the process. The Charset for the native encoding is used to read characters, lines, or stream lines from standard output.

This method delegates to inputReader(Charset) using the Charset named by the native.encoding system property. If the native.encoding is not a valid charset name or not supported the Charset#defaultCharset() is used.

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 Process. The input reader consumes and buffers bytes from the input stream. Bytes read from the input stream would not be seen by the reader and the buffer contents are unpredictable.

Returns:BufferedReader

a BufferedReader using the native.encoding if supported, otherwise, the Charset#defaultCharset()

Since
17
inputReaderback to summary
public final BufferedReader inputReader(Charset charset)

Returns a BufferedReader connected to the standard output of this process using a Charset. The BufferedReader can be used to read characters, lines, or stream lines of the standard output.

Characters are read by an InputStreamReader that reads and decodes bytes from this process getInputStream(). Bytes are decoded to characters using the charset; malformed-input and unmappable-character sequences are replaced with the charset's default replacement. The BufferedReader reads and buffers characters from the InputStreamReader.

The first call to this method creates the BufferedReader, if called again with the same charset the same BufferedReader is returned. It is an error to call this method again with a different charset.

If the standard output of the process has been redirected using ProcessBuilder.redirectOutput then the InputStreamReader will be reading from a null input stream.

The reader should be closed when it is no longer needed.

Otherwise, if the standard error of the process has been redirected using ProcessBuilder.redirectErrorStream then the input reader returned by this method will receive the merged standard output and the standard error of the process.

API Note

Use either this method or the input stream but not both on the same Process. The input reader consumes and buffers bytes from the input stream. Bytes read from the input stream would not be seen by the reader and the buffer contents are unpredictable.

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.

Parameters
charset:Charset

the Charset used to decode bytes to characters

Returns:BufferedReader

a BufferedReader for the standard output of the process using the charset

Exceptions
NullPointerException:
if the charset is null
IllegalStateException:
if called more than once with different charset arguments
Since
17
isAliveback to summary
public boolean isAlive()

Tests whether the process represented by this Process is alive.

Returns:boolean

true if the process represented by this Process object has not yet terminated.

Since
1.8
onExitback to summary
public CompletableFuture<Process> onExit()

Returns a CompletableFuture<Process> for the termination of the Process. The java.util.concurrent.CompletableFuture provides the ability to trigger dependent functions or actions that may be run synchronously or asynchronously upon process termination. When the process has terminated the CompletableFuture is completed regardless of the exit status of the process.

Calling onExit().get() waits for the process to terminate and returns the Process. The future can be used to check if the process is done or to wait for it to terminate. Cancelling the CompletableFuture does not affect the Process.

Processes returned from ProcessBuilder#start() override the default implementation to provide an efficient mechanism to wait for process exit.

API Note

Using onExit is an alternative to waitFor that enables both additional concurrency and convenient access to the result of the Process. Lambda expressions can be used to evaluate the result of the Process execution. If there is other processing to be done before the value is used then onExit is a convenient mechanism to free the current thread and block only if and when the value is needed.
For example, launching a process to compare two files and get a boolean if they are identical:

Process p = new ProcessBuilder("cmp", "f1", "f2").start(); Future<Boolean> identical = p.onExit().thenApply(p1 -> p1.exitValue() == 0); ... if (identical.get()) { ... }
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 waitFor() in a separate thread repeatedly until it returns successfully. If the execution of waitFor is interrupted, the thread's interrupted status is preserved.

When waitFor() returns successfully the CompletableFuture is completed regardless of the exit status of the process. This implementation may consume a lot of memory for thread stacks if a large number of processes are waited for concurrently.

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); }
public CompletableFuture<Process> onExit() {
   return delegate.onExit().thenApply(p -> this);
}

API Note

The process may be observed to have terminated with isAlive before the ComputableFuture is completed and dependent actions are invoked.

Returns:CompletableFuture<Process>

a new CompletableFuture<Process> for the Process

Since
9
outputWriterback to summary
public final BufferedWriter outputWriter()

Returns a BufferedWriter connected to the normal input of the process using the native encoding. Writes text to a character-output stream, buffering characters to provide for the efficient writing of single characters, arrays, and strings.

This method delegates to outputWriter(Charset) using the Charset named by the native.encoding system property. If the native.encoding is not a valid charset name or not supported the Charset#defaultCharset() is used.

The output writer should be closed when it is no longer needed.

Returns:BufferedWriter

a BufferedWriter to the standard input of the process using the charset for the native.encoding system property

Since
17
outputWriterback to summary
public final BufferedWriter outputWriter(Charset charset)

Returns a BufferedWriter connected to the normal input of the process using a Charset. Writes text to a character-output stream, buffering characters to provide for the efficient writing of single characters, arrays, and strings.

Characters written by the writer are encoded to bytes using OutputStreamWriter and the Charset are written to the standard input of the process represented by this Process. Malformed-input and unmappable-character sequences are replaced with the charset's default replacement.

The first call to this method creates the BufferedWriter, if called again with the same charset the same BufferedWriter is returned. It is an error to call this method again with a different charset.

If the standard input of the process has been redirected using ProcessBuilder.redirectInput then the OutputStreamWriter writes to a null output stream.

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 BufferedWriter with a PrintWriter provides efficient buffering and formatting of primitives and objects as well as support for auto-flush on line endings. Call the BufferedWriter#flush() method to flush buffered output to the process.

When writing to both getOutputStream() and either outputWriter() or outputWriter(Charset), BufferedWriter.flush should be called before writes to the OutputStream.

Parameters
charset:Charset

the Charset to encode characters to bytes

Returns:BufferedWriter

a BufferedWriter to the standard input of the process using the charset

Exceptions
NullPointerException:
if the charset is null
IllegalStateException:
if called more than once with different charset arguments
Since
17
pidback 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: toHandle().pid().

Returns:long

the native process id of the process

Exceptions
UnsupportedOperationException:
if the Process implementation does not support this operation
Since
9
quietCloseback to summary
private static IOException quietClose(Closeable c, IOException firstIOE)
supportsNormalTerminationback to summary
public boolean supportsNormalTermination()

Returns true if the implementation of destroy is to normally terminate the process, Returns false if the implementation of destroy forcibly and immediately terminates the process.

Invoking this method on Process objects returned by ProcessBuilder#start() and Runtime#exec return true or false depending on the platform implementation.

Implementation Specification

This implementation throws an instance of java.lang.UnsupportedOperationException and performs no other action.

Returns:boolean

true if the implementation of destroy is to normally terminate the process; otherwise, destroy forcibly terminates the process

Exceptions
UnsupportedOperationException:
if the Process implementation does not support this operation
Since
9
toHandleback to summary
public ProcessHandle toHandle()

Returns a ProcessHandle for the Process. Process objects returned by ProcessBuilder#start() and Runtime#exec implement toHandle as the equivalent of ProcessHandle.of(pid).

Implementation Specification

This implementation throws an instance of java.lang.UnsupportedOperationException and performs no other action. Subclasses should override this method to provide a ProcessHandle for the process. The methods pid, info, children, and descendants, unless overridden, operate on the ProcessHandle.

Returns:ProcessHandle

Returns a ProcessHandle for the Process

Exceptions
UnsupportedOperationException:
if the Process implementation does not support this operation
Since
9
tryWaitback to summary
private boolean tryWait()
waitForback to summary
public abstract int waitFor() throws InterruptedException

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the process has already terminated. If the process has not yet terminated, the calling thread will be blocked until the process exits.

Returns:int

the exit value of the process represented by this Process object. By convention, the value 0 indicates normal termination.

Exceptions
InterruptedException:
if the current thread is interrupted by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.
waitForback 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 Process object has terminated, or the specified waiting time elapses.

If the process has already terminated then this method returns immediately with the value true. If the process has not terminated and the timeout value is less than, or equal to, zero, then this method returns immediately with the value false.

Implementation Specification

The default implementation of this method polls the exitValue to check if the process has terminated.

Implementation Note

Concrete implementations of this class are strongly encouraged to override this method with a more efficient implementation.

Parameters
timeout:long

the maximum time to wait

unit:TimeUnit

the time unit of the timeout argument

Returns:boolean

true if the process has exited and false if the waiting time elapsed before the process has exited.

Exceptions
InterruptedException:
if the current thread is interrupted while waiting.
NullPointerException:
if unit is null
Since
1.8
waitForback to summary
public boolean waitFor(Duration duration) throws InterruptedException

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated, or the specified waiting duration elapses.

If the process has already terminated then this method returns immediately with the value true. If the process has not terminated and the duration is not positive, then this method returns immediately with the value false.

Implementation Specification

The default implementation of this method polls the exitValue to check if the process has terminated.

Implementation Note

Concrete implementations of this class are strongly encouraged to override this method with a more efficient implementation.

Parameters
duration:Duration

the maximum duration to wait; if not positive, this method returns immediately.

Returns:boolean

true if the process has exited and false if the waiting duration elapsed before the process has exited.

Exceptions
InterruptedException:
if the current thread is interrupted while waiting.
NullPointerException:
if duration is null
Since
24
waitForInternalback to summary
private Process waitForInternal()

Wait for the process to exit by calling waitFor. If the thread is interrupted, remember the interrupted state to be restored before returning. Use ForkJoinPool.ManagedBlocker so that the number of workers in case ForkJoinPool is used is compensated when the thread blocks in waitFor().

Returns:Process

the Process

java.lang back to summary

private Class Process.CharsetHolder

extends Object
Class Inheritance

A nested class to delay looking up the Charset for the native encoding.

Field Summary

Modifier and TypeField and Description
private static final Charset

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
pack-priv static Charset
nativeCharset()

Charset for the native encoding or {@link Charset#defaultCharset().

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

nativeCharsetback to summary
private static final Charset nativeCharset

Constructor Detail

CharsetHolderback to summary
private CharsetHolder()

Method Detail

nativeCharsetback to summary
pack-priv static Charset nativeCharset()

Charset for the native encoding or {@link Charset#defaultCharset().

java.lang back to summary

pack-priv Class Process.PipeInputStream

extends FileInputStream
Class Inheritance

An input stream for a subprocess pipe that skips by reading bytes instead of seeking, the underlying pipe does not support seek.

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public int
read()

Overrides java.io.FileInputStream.read.

Reads a byte of data from this input stream.

public int
read(byte[] b)

Overrides java.io.FileInputStream.read.

Reads up to b.length bytes of data from this input stream into an array of bytes.

public int
read(byte[] b, int off, int len)

Overrides java.io.FileInputStream.read.

Reads up to len bytes of data from this input stream into an array of bytes.

public long
skip(long n)

Overrides java.io.FileInputStream.skip.

Skips over and discards n bytes of data from the input stream.

Inherited from java.io.FileInputStream:
availableclosegetChannelgetFDreadAllBytesreadNBytestransferTo

Constructor Detail

PipeInputStreamback to summary
pack-priv PipeInputStream(FileDescriptor fd)

Method Detail

readback to summary
public int read() throws IOException

Overrides java.io.FileInputStream.read.

Doc from java.io.FileInputStream.read.

Reads a byte of data from this input stream. This method blocks if no input is yet available.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs.
readback to summary
public int read(byte[] b) throws IOException

Overrides java.io.FileInputStream.read.

Doc from java.io.FileInputStream.read.

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs.
readback to summary
public int read(byte[] b, int off, int len) throws IOException

Overrides java.io.FileInputStream.read.

Doc from java.io.FileInputStream.read.

Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs.
skipback to summary
public long skip(long n) throws IOException

Overrides java.io.FileInputStream.skip.

Doc from java.io.FileInputStream.skip.

Skips over and discards n bytes of data from the input stream.

The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. If n is negative, the method will try to skip backwards. In case the backing file does not support backward skip at its current position, an IOException is thrown. The actual number of bytes skipped is returned. If it skips forwards, it returns a positive value. If it skips backwards, it returns a negative value.

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.

Annotations
@Override
Exceptions
IOException:
if n is negative, if the stream does not support seek, or if an I/O error occurs.
java.lang back to summary

pack-priv Class Process.PipeOutputStream

extends FileOutputStream
Class Inheritance

An output stream for a subprocess pipe.

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public void
write(int b)

Overrides java.io.FileOutputStream.write.

Writes the specified byte to this file output stream.

public void
write(byte[] b)

Overrides java.io.FileOutputStream.write.

Writes b.length bytes from the specified byte array to this file output stream.

public void
write(byte[] b, int off, int len)

Overrides java.io.FileOutputStream.write.

Writes len bytes from the specified byte array starting at offset off to this file output stream.

Inherited from java.io.FileOutputStream:
closegetChannelgetFD

Constructor Detail

PipeOutputStreamback to summary
pack-priv PipeOutputStream(FileDescriptor fd)

Method Detail

writeback to summary
public void write(int b) throws IOException

Overrides java.io.FileOutputStream.write.

Doc from java.io.FileOutputStream.write.

Writes the specified byte to this file output stream. Implements the write method of OutputStream.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs.
writeback to summary
public void write(byte[] b) throws IOException

Overrides java.io.FileOutputStream.write.

Doc from java.io.FileOutputStream.write.

Writes b.length bytes from the specified byte array to this file output stream.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs.
writeback to summary
public void write(byte[] b, int off, int len) throws IOException

Overrides java.io.FileOutputStream.write.

Doc from java.io.FileOutputStream.write.

Writes len bytes from the specified byte array starting at offset off to this file output stream.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs.