Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Last active December 14, 2015 18:39
Show Gist options
  • Save jeffreyiacono/5131194 to your computer and use it in GitHub Desktop.
Save jeffreyiacono/5131194 to your computer and use it in GitHub Desktop.
forking and waiting with Ruby
pids = []
[0, 1, 2].each do |i|
pids << fork do
sleep 5 - i
puts "Hi from #{i}\n"
end
end
puts "done forking" # note: if you >> this file to another file, you will need $stdout.flush to ensure proper write ordering
pids.each { |pid| Process.wait pid }
puts "done with everything running"
#=> done forking
#=> Hi from 2
#=> Hi from 1
#=> Hi from 0
#=> done with everything running
pids = []
[0, 1, 2].each do |i|
pids << fork do
sleep 5 if i == 2
puts "Hi from #{i}\n"
end
end
puts "done forking" # note: if you >> this file to another file, you will need $stdout.flush to ensure proper write ordering
pids.each { |pid| Process.wait pid }
sleep 4
puts "done with everything running"
#=> Hi from 0 (immedate)
#=> Hi from 1 (immedate)
#=> done forking (immedate)
#=> Hi from 2 (5 seconds)
#=> done with everything running (4 seconds after 2 finishes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment