ruby – 如何等待衍生过程

ruby – 如何等待衍生过程,第1张

概述我正在尝试编写一个可以在后台执行 mongodb服务器的简单脚本.目前我使用Process.spawn方法.它工作但我必须等待一段时间让mongod完全运行(启动过程完成,数据库正在等待新的连接). def run! return if running? FileUtils.mkdir_p(MONGODB_DBPATH) command = "mongod --port 我正在尝试编写一个可以在后台执行 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

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

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

解决方法 这是一个等待子进程的一些输出的模式:

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.joinrescue EOFErrorensure  rd.closeendrun_and_wait_for_this( /waiting for connections on port xxxx/,'mongo','--port',port,'--dbpath',MONGODB_PATH,'--nojournal' )

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

总结

以上是内存溢出为你收集整理的ruby – 如何等待衍生过程全部内容,希望文章能够帮你解决ruby – 如何等待衍生过程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1280978.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存