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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)