2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

標準入出力でプロセス間通信

2
Posted at

昨日の記事 の続きみたいなものですが、spawnを使って標準入出力でプロセス間通信ができそうだなぁと思ったので実験してみました。

parent.rb
require "json"
pin1, pout1 = IO.pipe
pin2, pout2 = IO.pipe

spawn("ruby child.rb", :in => pin1, :out => pout2)
100.times { |i|
  obj = { "val" => i }
  data = JSON.generate(obj)
  pout1.puts data

  obj = JSON.parse(pin2.gets)
  puts obj["ret"]
}
child.rb
require 'json'

begin
loop {
  obj = JSON.parse(gets)
  ret = { "ret" => obj["val"] * 2 }
  puts JSON.generate(ret)
  STDOUT.flush
}
rescue
end

parent.rbを実行すると、0~198までの数字が羅列されると思います。パイプを2つ作ってそれぞれの片方をくっつける感じで作るのがミソですかね。

別にJSONにこだわらなくても、MessagePackなり、Protocol Bufferなりでデータシリアライズしてあげれば何でもいけると思います。

上の例だと、getsのところでブロックしちゃうので、非同期で動作させたい場合は工夫が必要かも。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?