How to communicate between processes in Ruby with sockets

In Ruby you can communicate between processes with sockets. This might be helpful in tests that validate parallel executions or custom finalization logic after the garbage collector. Here is an example how such an communication will look like:

require 'socket'
BUFFER_SIZE = 1024

# DGRAM has the advantage that it stops reading the pipe if the next messages starts. In case the message size is larger than the
# BUFFER_SIZE, you need to handle if you are reading another part of the current message or if you already reading the
# next message.
child, parent = Socket.pair :UNIX, :DGRAM, 0

fork do
  puts "Child is writing 'Hello'"
  child.write('Hello')
end

# .recv is blocking until the first message is written by the child
puts 'Waiting for the first message of the child'
message = parent.recv(BUFFER_SIZE)
puts "First message '#{message}' is received"

This will output:

Waiting for the first message of the child
Child is writing 'Hello'
First message 'Hello' is received

Note: The child process is killed once the parent process finishes. For certain cases you might want to wait until all child processes are finished.

require 'socket'

puts 'Starting parent'

fork do
  puts 'Starting child'
  at_exit { puts 'Child exited' }

  sleep(0.2) # This would be killed without Process.wait
end

# Defined after the fork, otherwise the handler is inherited
at_exit { puts 'Parent exited' }

Process.wait
Starting parent
Starting child
Child exited
Parent exited
Emanuel Over 3 years ago