Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Ruby Programming
Previous Page Home Next Page

Blocks and Subprocesses

IO.popen works with a block in pretty much the same way as 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}" }
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 .

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
pid = Process.wait
puts "Child terminated, pid = #{pid}, exit code = #{$? >> 8}"
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.

Ruby Programming
Previous Page Home Next Page

  Published under the terms of the Open Publication License Design by Interspire