How to wait for the spawned process
mongodb, process, ruby, spawn
Solution
Here is a pattern for waiting on 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 blocks until the process flushes the expected output into the pipe.
Problem
I'm trying to write a simple script which can execute mongodb server in the background. Currently I use `Process.spawn` method. It works but I have to wait some time for `mongod` to be process fully operational (boot process is completed 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 this script: https://github.com/lucassus/mongo_browser/blob/master/spec/support/mongod.rb#L22 Is it somehow possible to remove this ugly arbitrary `sleep 2` from this code? My first guess is to connect a pipe to the spawned process and wait until "waiting for connections on port xxxx" message is written to the pipe. But I don't know how to implement it.