ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> ruby-talk
ruby-talk
reading from an external process with IO.popen
by Robert Citek other posts by this author
Nov 5 2009 10:49AM messages near this date
11 | Re: reading from an external process with IO.popen
Hello all,

I'm trying to wrap my head around IO.popen with some simple examples
that send data to and read data from an
external process.  I've create a sample case in the shell like this:

$ { echo hello ; sleep 2 ; echo world; } | cat
hello
world

I've written the same in ruby like so, which works:

$ cat foo.rb
#!/usr/bin/env ruby
if $0 == __FILE__
 cat = IO.popen("cat", "w+") ;
 cat.puts("hello, ") ;
 puts(cat.gets) ;
 sleep 2 ;
 cat.puts("world") ;
 puts(cat.gets) ;
end

$ ./foo.rb
hello
world

However, if I change the cat command to a sed command, the ruby
version no longer works.  The command-line equivalent does work, but
the ruby version waits forever and has to be interrupted:

$ { echo hello ; sleep 2 ; echo world; } | sed -ne p
hello
world

$ cat foo.rb
#!/usr/bin/env ruby
if $0 == __FILE__
 cat = IO.popen("sed -ne p", "w+") ;
 cat.puts("hello, ") ;
 puts(cat.gets) ;
 sleep 2 ;
 cat.puts("world") ;
 puts(cat.gets) ;
end

$ ./foo.rb
./foo.rb:6:in `gets': Interrupt
       from ./foo.rb:6

Why does ruby work in the first case but wait forever in the second?

Using this version of ruby:

$ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]

Thanks in advance for any pointers to references.

Regards,
- Robert
Thread:
Robert Citek
Robert Klemme
Robert Citek
Robert Klemme
Robert Citek

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved