R
Robert Citek
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. =C2=A0I'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 =3D=3D __FILE__
=C2=A0cat =3D IO.popen("cat", "w+") ;
=C2=A0cat.puts("hello, ") ;
=C2=A0puts(cat.gets) ;
=C2=A0sleep 2 ;
=C2=A0cat.puts("world") ;
=C2=A0puts(cat.gets) ;
end
$ ./foo.rb
hello
world
However, if I change the cat command to a sed command, the ruby
version no longer works. =C2=A0The 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 =3D=3D __FILE__
=C2=A0cat =3D IO.popen("sed -ne p", "w+") ;
=C2=A0cat.puts("hello, ") ;
=C2=A0puts(cat.gets) ;
=C2=A0sleep 2 ;
=C2=A0cat.puts("world") ;
=C2=A0puts(cat.gets) ;
end
$ ./foo.rb
/foo.rb:6:in `gets': Interrupt
=C2=A0 =C2=A0 =C2=A0 =C2=A0from ./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
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. =C2=A0I'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 =3D=3D __FILE__
=C2=A0cat =3D IO.popen("cat", "w+") ;
=C2=A0cat.puts("hello, ") ;
=C2=A0puts(cat.gets) ;
=C2=A0sleep 2 ;
=C2=A0cat.puts("world") ;
=C2=A0puts(cat.gets) ;
end
$ ./foo.rb
hello
world
However, if I change the cat command to a sed command, the ruby
version no longer works. =C2=A0The 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 =3D=3D __FILE__
=C2=A0cat =3D IO.popen("sed -ne p", "w+") ;
=C2=A0cat.puts("hello, ") ;
=C2=A0puts(cat.gets) ;
=C2=A0sleep 2 ;
=C2=A0cat.puts("world") ;
=C2=A0puts(cat.gets) ;
end
$ ./foo.rb
/foo.rb:6:in `gets': Interrupt
=C2=A0 =C2=A0 =C2=A0 =C2=A0from ./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