7
9

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.

EventMachineを使ってpopen3で開いたプロセスの出力を受け取る

Last updated at Posted at 2014-06-08
#!/usr/bin/env ruby
# coding: utf-8

require 'open3'
require 'eventmachine'

# 受信用のクラス
class Recver < EventMachine::Connection
  # 初期化時に指定された引数を受け取る
  def initialize(arr)
    @arr = arr
  end

  # popen3したプロセスからの出力を受信
  def receive_data(data)
    res = data.scan(/^(\d+) bytes from (\S+?): icmp_seq=(\d+) ttl=(\d+) time=([\d\.]+) ms$/)
    res.each do |r|
      @arr.push(r[4].to_f)
    end
  end
end

arr = []
EM.run do
  # popen3のイベントとは別にタイマーを設定
  EM.add_periodic_timer(5) do
    # 5秒毎に出力結果をまとめたArrayを表示してからクリア
    p arr
    arr.clear
  end

  stdin, stdout, stderr = Open3.popen3("ping 8.8.8.8")
  stdout.sync = true
  # attach時に引数を指定する
  EM.attach(stdout, Recver, arr)
end
7
9
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
7
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?