#!/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
More than 5 years have passed since last update.
EventMachineを使ってpopen3で開いたプロセスの出力を受け取る
Last updated at Posted at 2014-06-08
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme