【问题标题】:Long running shell command in rubyruby 中长时间运行的 shell 命令
【发布时间】:2015-08-11 05:18:34
【问题描述】:

我想通过 ruby​​ 脚本在 Linux 上启动和管理长时间运行(几个小时)的 shell 命令。 我需要能够逐行解析输出,因为它们来了。不是当过程完成时。 如果我不喜欢输出,我需要能够终止命令并重新启动它。 我还需要知道进程是否终止。

我找到了 right_popen gem,但它已经 2 年没有更新并且没有文档。做这一切的最干净的方法是什么?

【问题讨论】:

  • 哪个操作系统?当您说“shell 命令”时,我假设我们在谈论 Linux / UNIX / BSD?
  • 是的,Linux。我为其他人编辑了问题。

标签: ruby shell process command


【解决方案1】:

我找到了一个解决方案,可以让我完成上述所有操作,所以我想我会与追随我的人分享它 :-) 我们通过 stdlib 中的伪终端来实现(不需要 gem)。

下面是我需要的代码示例:

require 'pty'

cmd = 'for i in 1 2 3 4 5; do echo $i; sleep 1; done'
PTY.spawn cmd do |r, w, pid|
  begin
    r.sync
    r.each_line do |l|
      # Process each line immediately
      line = l.strip
      puts line
      if line == '3'
        # We kill the command on 3, because 3s are evil...
        ::Process.kill('SIGINT', pid)
      end
    end
  rescue Errno::EIO => e
    # Linux raises this error when the command ends
    puts "COMMAND DIED"
  ensure
    # Wait for the process to end before we go on
    ::Process.wait pid
    puts "WE ARE CLEAR"
  end
end

输出:

1
2
3
COMMAND DIED
WE ARE CLEAR

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 2012-04-26
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多