# Chaining processes, Process.waitpid

**URL:** <https://www.ruby-forum.com/t/chaining-processes-process-waitpid/91991>\
**Category:** Ruby\
**Created:** [April 14, 2007, 1:55am UTC](https://www.ruby-forum.com/t/chaining-processes-process-waitpid/91991 "2007-04-14T01:55:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![samoht](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ac8455/32.png) [@samoht](https://www.ruby-forum.com/u/samoht)\
**Post date:** [April 14, 2007, 1:55am UTC](https://www.ruby-forum.com/t/chaining-processes-process-waitpid/91991/1 "2007-04-14T01:55:37Z")

</div>

Hello,

for chaining processes in a way, that the output of one process feeds  
the input of another one like in that example …

#\

# transformation ‘foo’ -\> ‘fee’ -\> ‘tee’:

chain\_processes(lambda { exec(‘echo’, ‘foo’) },  
lambda { exec(‘sed’, ‘s|o|e|g’) }) do  
system(‘sed’, ‘s|f|t|g’)  
end  
#//

… I came to that solution:

#\  
def chain\_processes(\*processes, &block)  
saved\_stdin = $stdin.clone  
threads = []  
this, \*remaining = processes + (block ? [block] : [])  
while [] != remaining  
rd, wr = IO.pipe  
child = fork  
if !child  
rd.close  
$stdout.reopen(wr)  
exit this[]  
end  
wr.close  
$stdin.reopen(rd)  
threads \<\< Thread.new { Process.waitpid(child) }  
this, \*remaining = remaining  
end

this[]  
threads.each { |t| t.join }  
$stdin.reopen(saved\_stdin)  
end  
#//

That seems also to work without Process.waitpid(child). When is it  
really necessary to wait for the children? How should an example look  
like which breaks without using Process.waitpid or Process.wait?

Regards  
Thomas
