Posted about 1 month ago. Visible to the public.

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:

Copy
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:

Copy
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.

Copy
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
Copy
Starting parent Starting child Child exited Parent exited

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Emanuel De
Last edit:
about 1 month ago
by Tobias Kraze
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more