4

我正在尝试编写一个可以在后台执行 mongodb 服务器的简单脚本。目前我使用Process.spawn方法。它可以工作,但我必须等待一段时间mongod才能完全运行(启动过程已完成,数据库正在等待新连接)。

  def run!
    return if running?

    FileUtils.mkdir_p(MONGODB_DBPATH)

    command = "mongod --port #{port} --dbpath #{MONGODB_DBPATH} --nojournal"
    log_file = File.open(File.expand_path("log/test_mongod.log"), "w+")
    @pid = Process.spawn(command, out: log_file)

    # TODO wait for the connection (waiting for connections on port xxxx)
    sleep 2

    yield port if block_given?
  end

这是完整的脚本: https ://github.com/lucassus/mongo_browser/blob/master/spec/support/mongod.rb#L22

sleep 2是否有可能从这段代码中删除这个丑陋的任意?

我的第一个猜测是将管道连接到生成的进程并等待“等待端口 xxxx 上的连接”消息写入管道。但我不知道如何实现它。

4

1 回答 1

5

这是等待子进程某些输出的模式:

def run_and_wait_for_this regexp_to_wait_for, *cmd
  rd, wr = IO.pipe
  pid = Process.spawn(*cmd, out: wr)
  pid_waiter = Thread.new { Process.wait(pid); wr.close }
  thr = Thread.new do
    buffer = ''
    until buffer =~ regexp_to_wait_for
      buffer << rd.readpartial(100)
    end
  end
  thr.join
rescue EOFError
ensure
  rd.close
end

run_and_wait_for_this( /waiting for connections on port xxxx/, 'mongo', '--port', port, '--dbpath', MONGODB_PATH, '--nojournal' )

它会阻塞,直到进程将预期的输出刷新到管道中。

于 2012-11-19T15:11:27.057 回答