NebulaFox
NebulaFox

Reputation: 8313

Change STDIN with a pipe and it's a directory

I have this

pipe_in, pipe_out = IO.pipe

fork do
    # child 1
    pipe_in.close
    STDOUT.reopen pipe_out
    STDERR.reopen pipe_out
    puts "Hello World"
    pipe_out.close
end

fork do
    # child 2
    pipe_out.close

    STDIN.reopen pipe_in

    while line = gets
        puts 'child2:' + line
    end

    pipe_in.close
end

Process.wait
Process.wait

get will always raise an error saying "gets: Is a directory", which doesn't make sense to me. If I change gets to pipe_in.gets it works. What I want to know is, why doesn't STDIN.reopen pipe_in and gets not work?

Upvotes: 1

Views: 396

Answers (1)

DigitalRoss
DigitalRoss

Reputation: 146073

It works for me, with the following change:

     pipe_in.close
 end

+pipe_in.close
+pipe_out.close
+
 Process.wait
 Process.wait

Without this change, you still have the pipes open in the original process, so the reader will never see an end of file. That is, process doing the wait still had the write pipe open leading to a deadlock.

Upvotes: 2

Related Questions