How to wait for a vicious process

I am trying to write a simple script that can execute a mongodb server in the background. I am currently using the Process.spawn method. It works, but I have to wait a while for mongod to work completely (the download process is complete and the database is waiting for new connections).

  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 

Here is the full script: https://github.com/lucassus/mongo_browser/blob/master/spec/support/mongod.rb#L22

Is it possible to remove this ugly arbitrary sleep 2 from this code?

My first assumption is to connect the pipe to the spawned process and wait for the message "Waiting for connections on port xxxx" to be written to the pipe. But I do not know how to implement it.

+4
source share
1 answer

Here is an example of waiting for some output from a child process:

 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' ) 

It is blocked until the process displays the expected result in the channel.

+5
source

Source: https://habr.com/ru/post/1446959/


All Articles