5
6

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.

Rubyで親子プロセス間の大量データやりとりを、パイプで実現するサンプル

Last updated at Posted at 2015-02-27

Rubyで親子プロセス間の大量データやりとりを、パイプで実現するサンプルです。
ruby 1.9で動作確認しています

ポイントとしては、
パイプのサイズ以上のデータをやりとりする場合は、読み取り側で読んであげないと、書き込み側がブロックしてしまうので、そうならないようにしているところです。


# -*- coding: utf-8 -*-

# 長い文字列の準備
str = "0123456789"
longstr = ""
1000.times {longstr += str}

# 子プロセスから結果をもらうパイプ
read_pipe, write_pipe = IO.pipe 

pid = nil

# 子プロセス生成
pid = fork do
  #子プロセス側の読み込み口は不要なので閉じる
  read_pipe.close

  #パイプに長い文字列を書き込む
  5.times do
    puts "Child write #{longstr.size} chars"
    write_pipe.write(longstr)
    sleep 1
  end

  #子プロセス側の書き込みパイプを閉じる
  write_pipe.close
end

# 親プロセス
unless (pid.nil?)
  #少し待つ
  sleep 1

  #親プロセス側の書き込み口は不要なので閉じる
  write_pipe.close

  #パイプからデータを抜く
  begin 
    while true
      tmp = read_pipe.read_nonblock(10000)
      puts "Parent read #{tmp.size} chars"
      sleep 1
    end
  rescue EOFError => e # 読み込み完了
    # 子プロセスが書き込み口をcloseすると、EOFがパイプに書かれ、
    # read_nonblockがそれを見てEOFErrorの例外をだす。
    # これを補足することにより書き込みが終わったことを判断。
  end

  #親プロセス側の読み込み口を閉じる
  read_pipe.close

  #プロセスの終了を待つ
  paid,status = Process.wait2(pid)
end


実行結果

Child write 10000 chars
Child write 10000 chars
Parent read 10000 chars
Child write 10000 chars
Parent read 10000 chars
Parent read 10000 chars
Child write 10000 chars
Parent read 10000 chars
Child write 10000 chars
Parent read 10000 chars
5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?