LoginSignup
2
2

More than 5 years have passed since last update.

Rubyでtail -fする

Posted at

書き込まれ続けているファイルに対してtail -fのような感じで末尾の出力を読み取り続ける方法。

方法

tail_f.rb
f=open(ARGV[0])
begin
  f.sysseek(-32, IO::SEEK_END)    # 末尾から32byte取得
rescue
  f.sysseek(0, IO::SEEK_SET)      # ファイルが32byte以下だった場合は、先頭から
end

while true
  print f.sysread(10) rescue nil
end

上記のファイルを以下のように実行

ruby tail_f.rb test

別の端末でirbを立ち上げて挙動確認。

io = File.open("test", 'a')
=> #<File:test>
irb(main):003:0> io.puts "message ---- "; io.flush
=> #<File:test>

io.flushが呼ばれたタイミングで、元のtail_fを実行した端末に結果が出力される。

参考

こちらを参考にしました。

2
2
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
2