In article <491789d8ea792_9659445a4451e7 / redmine.ruby-lang.org>,
  Michal Suchanek <redmine / ruby-lang.org> writes:

> Bug #738: Repeated calls to popen cause thread problems
> http://redmine.ruby-lang.org/issues/show/738

> Also there is a problem with the pipe one gets from
> popen. Using the same IO in both threads is the only safe
> way in MRI (although caution would advise to duplicate the
> IO as shown in testt.rb). Duplicating the IO results in
> deadlock error within about 200 calls in any recent MRI
> Ruby I tried but is required in JRuby.

"IO::for_fd analyzer.fileno" in testt.rb is dangerous.
It makes two IO objects, X and Y, share single file
descriptor N.

When X is closed, N is closed.  Since Y refer N, Y doesn't
work.

However, Y doesn't know that N is closed.  Y still refer N.

If the process opens a file, creates a pipe or whatever
allocates a file descriptor, the allocated file descriptor
may be N because N is closed.

After that, operations on Y is done for the newly allocated
file descriptor.  For example, if Y is closed, the new file
descriptor is closed.

So, don't duplicate IO as "IO::for_fd analyzer.fileno".

I'm not sure why JRuby works well with that.

Note that duplex IO.popen returns an IO object which have
two file descriptors.  So the above description is not
accurate.
-- 
Tanaka Akira