Created
June 8, 2014 10:28
-
-
Save m-mizutani/2b6bbbd501b9aa079ea2 to your computer and use it in GitHub Desktop.
Eventmachine with forked process by popen3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment