Week 129 — How can one create and start a new process?
Question of the Week #129
How can one create and start a new process?
6 Replies
The JDK provides the
ProcessBuilder
to execute other programs. It is possible to create a ProcessBuilder
by specifying the program and the arguments in the constructor. After optionally configuring the ProcessBuilder
, the start()
method can be used to start the process.
For example, the following code runs ip route
and prints the output to the console:
Instead of printing the routes to the console, the output can be accessed programmatically as well:
Or it can be written to a file:
In addition to configuring stdin/stdout/stderr, it also prvides methods for accessing environment variables and the working directory:
ProcessBuilder
also provides a static
method that can be used to compose multiple ProcessBuilder
s similar to the usage of the |
operator in POSIX shells:
Java also provides other mechanisms to start processes like
Runtime#exec
but these provide less control and can be harder to use when arguments may contain spaces or similar.📖 Sample answer from dan1st
Using ProcessBuilder class
String command = "This is a process”;
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start()
;
Submission from riti0710
To start a new process in java, you can use either the
ProcessBuilder
class or the Runtime.exec()
method.
Both methods allow you to create and start a new process from your program, but ProcessBuilder
is more flexible and preferred for most use cases.
ProcessBuilder Approach
Similarly, you can set the process environment and redirect its input/output streams with something like this:
Runtime.exec() Approach
This method also returns a Process
object similar to ProcessBuilder
, but is less flexible compared to ProcessBuilder
. (e.g. environment customization and I/O redirection are less convenient).
----------------
Both enlisted approachs return a Process
object, which provides methods to:
- Read the process’s output (getInputStream()
)
- Write to the process’s input (getOutputStream()
)
- Read the process’s error stream (getErrorStream()
)
- Wait for the process to finish (waitFor()
)
- Get the exit code (exitValue()
)
- Destroy the process (destroy()
)
NOTE: Name of methods getInputStream()
and getOutputStream()
may feel counterintuitive as they are named from the perspective of the java program, not the external process. getInputStream()
returns InputStream
which essentially means Output of Program -> Java
and getOutputStream()
returns OutputStream
which means Java -> Input of Program
.Practically, you'd always want to
ProcessBuilder
as it's more configurable. You'd only see and use Runtime.exec()
for simpler cases or while maintaining legacy code prior to Java 5.
⭐ Submission from daysling