# Waiting for multiple child processes to finish

**URL:** <https://www.ruby-forum.com/t/waiting-for-multiple-child-processes-to-finish/75790>\
**Category:** Ruby\
**Created:** [November 13, 2006, 3:18pm UTC](https://www.ruby-forum.com/t/waiting-for-multiple-child-processes-to-finish/75790 "2006-11-13T15:18:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [November 13, 2006, 3:18pm UTC](https://www.ruby-forum.com/t/waiting-for-multiple-child-processes-to-finish/75790/1 "2006-11-13T15:18:53Z")

</div>

## Why does this not work (it waits for each process to finish before launching the next):

$stdout.sync = true

10.times {|i|  
pid = Process.fork {  
puts “launching process #{i}”  
3.times {  
sleep 0.5  
puts “hello from process #{i}”  
}  
}  
Thread.new { Process.waitpid(pid) }.join  
}

## puts “done!”

## but this does:

$stdout.sync = true

pids = []  
10.times {|i|  
pids \<\< Process.fork {  
puts “launching process #{i}”  
3.times {  
sleep 0.5  
puts “hello from process #{i}”  
}  
}  
}

pids.each {|pid| Thread.new { Process.waitpid(pid) }.join }  
puts “done!”

---

<div class="post-metadata">

**Author:** ![Martin\_DeMello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f17d59/32.png) [@Martin\_DeMello](https://www.ruby-forum.com/u/Martin_DeMello)\
**Post date:** [November 13, 2006, 3:30pm UTC](https://www.ruby-forum.com/t/waiting-for-multiple-child-processes-to-finish/75790/2 "2006-11-13T15:30:56Z")

</div>

On 13/11/06, Martin DeMello [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> puts "hello from process #{i}"
> 
> ```
> 
> $stdout.sync = true  
> }
> 
> ## pids.each {|pid| Thread.new { Process.waitpid(pid) }.join } puts “done!”

The join in the first solution forces the thread (and forked process)  
to finish before continuing onto starting the next fork. In the second  
solution all the processes are forked first before waiting. You can  
probably rewrite that last loop simply as:  
pids.each{|pid| Process.waitpid(pid)}

Farrel
