【问题标题】:Spawn process thats loops and get stdout continuosly in ruby生成循环并在 ruby​​ 中连续获取标准输出的进程
【发布时间】:2013-12-04 14:24:02
【问题描述】:

我需要在 ruby​​ 脚本中创建一个程序。 这个程序会定期打印一个 JSON 并且在主脚本中我需要拦截它并进行计算。 谢谢

类似这样的:

MAIN:
   Spawn a process
      //This generates stdout periodically
   //End call
   Intercept its stdout
   //REST of the code

怎么做? 我需要使用事件机器吗?有点?

我用这段代码澄清一下

timer = EventMachine.add_periodic_timer POLLING_INTERVAL do
    if memcached_is_running
      ld 'reading from device'
      begin

          IO.popen("HostlinkPollerLight -p #{SERIAL_PORT} -v #{SERIAL_BAUDRATE} -r #{MODEL_CONFIG} 2> /dev/null") do |payload|
                  $_data = JSON.parse payload.readlines[0]
          end


        if $data['success']

          memcache.set( MEMCACHE_DATA_KEY, _to_json( $data[ 'result' ], _mapping ))
          timer.interval = POLLING_INTERVAL
        else
          log_this " read fault: error_code #{$data['fault']}"
          timer.interval = FAULT_INTERVAL
        end
      rescue Errno::ENOENT
        log_this 'Unable to read  output'
      rescue JSON::ParserError
        log_this 'Malformed  data'
      end
    else
      timer.interval = FAULT_INTERVAL
      system("on_red_led.sh 2")
    end
    log_this "elapsed time: #{Time.now.to_f - delta}"
    ld "## end read: #{counter}"

    counter += 1
end

我只需要在程序使用 popen 打开时 spwan 一次,并在每次打印 stdout 时获取 stdout。

【问题讨论】:

  • 你的问题是?

标签: ruby process spawn


【解决方案1】:

我这样做的方法是,我创建一个类,该类创建一个具有无限循环的新线程,它会改变对象的实例变量。然后我可以通过它的 getter 访问这些变量。示例:

class Stopwatch
  def initialize
    @seconds = 0
  end

  def start
    @thread = Thread.new do
      loop {
        sleep(1)
        @seconds += 1
      }
    end
  end

  def seconds
    @seconds
  end

  def stop
    @thread.kill
  end

  def reset
    @seconds = 0
  end
end

stoper = Stopwatch.new
stoper.start

sleep(5)
stoper.seconds #=> 5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2018-03-08
    • 1970-01-01
    • 2010-11-19
    • 2019-02-10
    • 1970-01-01
    相关资源
    最近更新 更多