Read more

How to communicate between processes in Ruby with sockets

Emanuel
January 12, 2021Software engineer at makandra GmbH

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"
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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
Posted by Emanuel to makandra dev (2021-01-12 11:43)