LoginSignup
2
1

More than 3 years have passed since last update.

rubyでノンブロッキングなread

Last updated at Posted at 2018-01-11

https://docs.ruby-lang.org/ja/latest/method/IO/i/read_nonblock.html
IO#read_nonblockなるものがあるのでこれを使う。

1秒毎に入力をチェックして、入力があれば入力されたデータを出力し、入力されていなければnoを出力するサンプル。
read_nonblockして空だったときにIO::EAGAINWaitReadableが発生するので拾って無視している。


require 'socket'

reader, writer = IO.pipe

Thread.new do
  while data = gets do
    writer.puts(data)
  end
end

while true do
  sleep 1
  begin
    puts reader.read_nonblock(100)
  rescue IO::EAGAINWaitReadable
    puts 'no'
  end
end
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