Skip to content

Instantly share code, notes, and snippets.

@AlexB52
Last active November 11, 2020 20:28
Show Gist options
  • Save AlexB52/8f771020136eb60b7a4ab24ae5d779d8 to your computer and use it in GitHub Desktop.
Save AlexB52/8f771020136eb60b7a4ab24ae5d779d8 to your computer and use it in GitHub Desktop.
Running sub-processes in Ruby

Resources:

Starting a Process and killing it

Process Ruby Doc

The child process can exit using Kernel.exit! to avoid running any at_exit functions. The parent process should use Process.wait to collect the termination statuses of its children or use Process.detach to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.

To Be Tested

def start
  @pid = IO.popen("sleep").pid
  # @pid = fork { `sleep` }
end

def stop
  Process.kill(9, @pid)
  Process.wait(@pid)
end

Synchronous calls

From article

Method #1: The Backtick Operator

returns the output of the command

`ls`
%x|ls|

Method #2: Kernel#system

returns boolean if the command is successful

  • true (command worked)
  • false (command errrors out)
  • nil (command not found)
system("ls")

Forks

Method #3: Kernel#fork (aka Process.fork)

This will run ls on another process & display its output

pid = fork { exec("ls") }
Process.wait(pid)

From article

Method #4: Opening a pipe

To Do

Method #5: Forking to a pipe

To Do

From article

Method #6: Open3

r = IO.popen("irb", "r+")
r.write "puts 123 + 1\n"
3.times { puts r.gets }
r.write "exit\n"

Method #7: PTY

Method #8: Shell

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment