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:
Copyrequire '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:
CopyWaiting 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.
Copyrequire '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
CopyStarting parent Starting child Child exited Parent exited
Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).