Advanced examples

Output to pipe

Note that if you just want to get the output of a command, the backtick method on Kernel may be a better fit.

Write to stdin

process=ChildProcess.build("cat")out=Tempfile.new("duplex")out.sync=trueprocess.io.stdout=process.io.stderr=outprocess.duplex=true# sets up pipe so process.io.stdin will be available after .start
process.startprocess.io.stdin.puts"hello world"process.io.stdin.closeprocess.poll_for_exit(exit_timeout_in_seconds)out.rewindout.read#=> "hello world\n"

Pipe output to another ChildProcess

search=ChildProcess.build("grep",'-E',%w(redismemcached).join('|'))search.duplex=true# sets up pipe so search.io.stdin will be available after .start
search.io.stdout=$stdoutsearch.startlisting=ChildProcess.build("ps","aux")listing.io.stdout=search.io.stdinlisting.startlisting.waitsearch.io.stdin.closesearch.wait

Prefer posix_spawn on *nix

If the parent process is using a lot of memory, fork+exec can be very expensive. The posix_spawn() API removes this overhead.

ChildProcess.posix_spawn=trueprocess=ChildProcess.build(*args)

Ensure entire process tree dies

By default, the child process does not create a new process group. This means there's no guarantee that the entire process tree will die when the child process is killed. To solve this:

process=ChildProcess.build(*args)process.leader=trueprocess.start

Detach from parent

Invoking a shell

As opposed to Kernel#system, Kernel#exec et al., ChildProcess will not automatically execute your command in a shell (like /bin/sh or cmd.exe) depending on the arguments.
This means that if you try to execute e.g. gem executables (like bundle or gem) or Windows executables (with .com or .bat extensions) you may see a ChildProcess::LaunchError.
You can work around this by being explicit about what interpreter to invoke: