I want to communicate with Ruby repeatedly between processes.

Asked 2 years ago, Updated 2 years ago, 35 views

require 'thread'
require 'time'
require 'find'

read, write = IO.pipe

# child processing
fork do
  testArray=Array.new
  inArray = {
      —id=>1000,
      —type=>"A"
  }
  testArray <<inArray
  testArray <<inArray

  # Close as it is not read by child process
  read.close
  loop do
      str = Marshall.dump (testArray)
      write.puts str
#      write.close
      sleep5
  end

  write.close
end

# parent process processing
# Close as no parent writes
write.close
Thread.new do
  loop do
    read.read
    result=Marshal.load(message)
  end

end

# Waiting for process processing to end
Process.waitall

I'm studying fork.
You want to pass data from the child process to the parent process.
The parent creates IO.pipe and tries to send serialized data to the parent repeatedly.
If there is no loop do processing, write.close with child
The parent was able to retrieve the value.
If you want to repeat the notification,
because "write.close" results in an error in "write.puts" When I commented out "write.close", I couldn't do "read.read", so
Process child processes

read.close
  loop do
      str = Marshall.dump (testArray)
      write.puts str + 'end' ★
      sleep5
  end

Parent Process Processing

loop do
    read.read
    while message=read.gets('end')★
      message.delete('end') ★
      results=Marshal.load(message)
    end
  end

Now that I've done this,
The first write from the child was successful and
For the second time, Marshall.load and later will not be processed.
message.delete('end') ★

Isn't this the way it is made when writing and reading repeatedly?

ruby

2022-09-30 19:27

1 Answers

Since I am using putts, I think it would be better to use read.gets("end\n",chomp:true).In this case, message.delete('end') is no longer required (it's a snakefoot, but it's not delete but message.slice!('end')), and I don't think read on the parent process side is necessary.

Serialized data is binary, so I think the transmitted data length (byte length) + serialized data is better.

sample code:
https://paiza.io/projects/e/fV059c6YMuiay9wT7bxjwA

This post was posted as a community wiki based on @metropolis' comments.


2022-09-30 19:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.