Execing Processes in Ruby
Here’s the translation of the Go code to Ruby, with explanations adapted for Ruby:
Our example demonstrates how to replace the current Ruby process with another process using Ruby’s implementation of the classic exec
function.
require 'shellwords'
# For our example we'll exec `ls`. Ruby can find the binary
# automatically, so we don't need to specify the full path.
binary = 'ls'
# Ruby's exec requires arguments as separate parameters
# (as opposed to one big string). We'll give `ls` a few
# common arguments.
args = ['ls', '-a', '-l', '-h']
# In Ruby, the current environment is automatically passed to
# the new process, so we don't need to explicitly set it.
# Here's the actual `exec` call. If this call is successful,
# the execution of our Ruby process will end here and be
# replaced by the `ls -a -l -h` process.
exec(binary, *args)
# This line will never be reached if exec is successful
puts "Exec failed!"
When we run our program it is replaced by ls
.
$ ruby execing_processes.rb
total 16
drwxr-xr-x 4 user 136B Oct 3 16:29 .
drwxr-xr-x 91 user 3.0K Oct 3 12:50 ..
-rw-r--r-- 1 user 1.3K Oct 3 16:28 execing_processes.rb
Note that Ruby’s exec
function behaves similarly to the Unix exec
system call. It replaces the current process with a new one. If you need to start a new process without replacing the current one, you can use system
or backticks () for command execution, or
Process.spawn` for more control over the new process.
Ruby also provides fork
which can be used to create a new process that is a copy of the current one. This is often used in combination with exec
to create a new process running a different program.