IO.popen
works with a block in pretty much the same way as
File.open
does.
Pass
popen
a command, such as
date
, and the
block will be passed an
IO
object as a parameter.
IO.popen ("date") { |f| puts "Date is #{f.gets}" }
|
produces:
Date is Sun Jun 9 00:08:50 CDT 2002
|
The
IO
object will be closed automatically when the code block
exits, just as it is with
File.open
.
If you associate a block with
Kernel::fork
, the code in the
block will be run in a Ruby subprocess, and the parent will continue
after the block.
fork do
puts "In child, pid = #$$"
exit 99
end
pid = Process.wait
puts "Child terminated, pid = #{pid}, exit code = #{$? >> 8}"
|
produces:
In child, pid = 31849
Child terminated, pid = 31849, exit code = 99
|
One last thing. Why do we shift the exit code in
$?
8 bits to
the right before displaying it? This is a ``feature'' of Posix
systems: the bottom 8 bits of an exit code contain the reason the
program terminated, while the higher-order 8 bits hold the actual
exit
code.