From: Brian Candler Date: 2003-05-08T06:58:18+09:00 Subject: Re: capture output On Wed, May 07, 2003 at 10:58:38PM +0900, Simon Strandgaard wrote: > [snip popen talk] > > Sorry.. I never thought it would be that hard to explain > my problem :-) > > > I embed ruby into C++. The "void main" is located in the frontend. > Right now everything is running in the same process. > > User supplyed ruby-code is executed in the same process... > its NOT executed as a child-process, thus popen3 is not possible. Fine, but you were the one who gave the example of "vim running a process and capturing its output". That is most definitely a child process. If you have written a C++ program, and have embedded the Ruby interpreter in it, then by default they will share the same stdin/stdout/stderr. The Ruby code can also write to stdout and stderr. Why should it not? If you want to intercept it, so that when Ruby does "puts" it goes into a string, then you can redirect Ruby's output stream as explained before: $defout = StringIO.new(...) puts "Hello" If the Ruby process spawns a child, using backtick or Kernel#system, THEN IT IS A CHILD of your C++ program (the parent process is one and the same). If you don't use popen then it will share the same Unix file descriptors for stdout and stderr. This is how Unix works. If you have done $stdout = File.new("foo","w") then this will in fact redirect stdout, because $stdout in Ruby is a hooked variable: by assigning to $stdout you are not only changing it to point to a new Ruby object, but Ruby will also use dup2() to reassign Unix file descriptor 1 (i.e. Unix's view of "the standard output of this process" will be changed). Hence if the child writes to its stdout, it will end up getting written to that file. However it cannot work if the object you assign it to is a pure Ruby object like StringIO. This is exactly the same as if you were to call fork() and exec() directly from your C(++) program. It inherits stdout/stderr, unless you create an explicit pipe or set of pipes between your parent and its child to read the child's output. I'm sorry, frustration is starting to set in for me. For my sanity I think I will have to ignore this thread now. Brian.