Sunday, December 10, 2006

[uncomplete] Pages 139-41: Running multiple processes - Spawning new processes


Listen to this article.

Value: Average

Level: Hard

Summary:
Sometimes you may want to split a task into several process-sized chunks, or perhaps you need to run a separate process that was not written in Ruby. You have several ways to spawn a separate process.
The method Kernel.system executes the given command in a subprocess, and you can capture the standard output of a subprocess using the  backquote (or backtick) method. IO.popen method runs a command as a subprocess and connects that subprocess's standard input and standard output to a Ruby IO object: every input you'll give this object will be given to the subprocess, and every subprocess output will be available in the object. [On some platforms, popen has one more twist. If the command you pass it is a single minus sign ( – ), popen will fork a new Ruby interpreter.] [add examples] [add references] In addition to the popen method, some platforms support the methods Kernel.fork, Kernel.exec, and IO.pipe. The file-naming convention of many IO methods and Kernel.open will also spawn subprocesses if you put a | as the first character of the filename.

Memo: If the subprocess response output doesn't get flushed, your program will hang forever. Note that you cannot create pipes using File.new; it's just for files.

Example:

system("date")
myname = `uname`
puts "My name is " + myname
date_in_array = IO.popen("date") {|a| a.readlines}
print date_in_array

Reported errata (at 10/17/06 14:17:18 PDT): 2
* #1943 #2815 both regard the obvious lack of a program called "pig" on some systems.

Errata I found: 0

My suggestions to the author: 1
* Give more details on IO#close_write.

Doubts: 2
* Is it possible to give options to a command stored in an IO object ?
* When I run "IO.popen("-")" in my IRb, input from my keyboard seems not to flow properly. Why ?

0 Comments:

Post a Comment

<< Home