Child Process is a Vert.x component for spawning OS child processes.
To use Child Process, add the following dependency to the dependencies section of your build descriptor:
pom.xml
):<dependency>
<groupId>com.julienviet</groupId>
<artifactId>childprocess-vertx-ext</artifactId>
<version>2.0.0</version>
</dependency>
build.gradle
file):dependencies {
compile 'com.julienviet:childprocess-vertx-ext:2.0.0'
}
You can spawn child processes with the Process.create
and start
methods:
ProcessBuilder processBuilder = Process.create(vertx, "ls");
// Start the process
Future<Void> fut = processBuilder.start();
the future returned by start
completes when the process has started or failed
you can give arguments to child processes
Process.create(vertx, "ls", Arrays.asList("-lh", "/usr")).start();
by default child processes use the current process environment options, you can pass key-value pairs as new environment variables
Map<String, String> env = new HashMap<>();
env.put("MY_VAR", "whatever");
Process.create(vertx, "ls", new ProcessOptions().setEnv(env)).start();
Process.env
gives you the current process environment key-value pairs
ProcessOptions options = new ProcessOptions().setEnv(Process.env());
Process.create(vertx, "ls", options).start();
By default, the child processes uses the current process current working directory, the
setCwd
option overrides it
ProcessOptions options = new ProcessOptions().setCwd("/some-dir");
Process.create(vertx, "ls", options).start();
The child process streams are available as
ProcessBuilder processBuilder = Process.create(vertx, "cat");
processBuilder.startHandler(process -> {
process.stdout().handler(buff -> {
System.out.println(buff.toString());
});
process.stdin().write(Buffer.buffer("Hello World"));
});
processBuilder.start();
Calling kill
kills the child process, on POSIX it sends the
SIGTERM
signal.
Process
.create(vertx, "cat")
.startHandler(process -> {
process.stdout().handler(buff -> {
System.out.println(buff.toString());
});
process.stdin().write(Buffer.buffer("Hello World"));
// Kill the process
process.kill();
})
.start();
Child processes can also be forcibly killed
Process
.create(vertx, "cat")
.startHandler(process -> {
process.stdout().handler(buff -> {
System.out.println(buff.toString());
});
process.stdin().write(Buffer.buffer("Hello World"));
// Kill the process forcibly
process.kill(true);
}).start();
You can be aware of the child process termination
Process
.create(vertx, "sleep", Arrays.asList("2"))
.startHandler(process -> {
process.exitHandler(code -> {
System.out.println("Child process exited with code: " + code);
});
})
.start();