IO.popen(), Timeout, broken pipe

Hey everybody,

I am having some weird problems with the Timeout module and IO.popen.

Basically, what I want to do is: Sign some data by gpg. For some reason, gpg
hangs sometimes and I want to have a timeout. If gpg does not return after
some time, I want to abort.

My code looks like this:

  def pgpsign(msg)

    signed_msg = msg

    begin
      Timeout::timeout(@gpgtimeout) {
        io = IO.popen("#{@gpg} --clearsign --home=#{@gpghome}","w+") or return msg
        io.puts msg
        io.close_write
        signed_msg = io.readlines.to_s
        io.close
      }
    rescue
      puts "GPG timed out. Sending unsigned message."
    end
  
    return signed_msg

  end

However, if gpg really times out, I will get the following messages

  fo/usr/lib/ruby/1.8/timeout.rb:60:in `puts': execution expired (Timeout::Error)
     from /home/flo/bin/test.rb:423:in `pgpsign'
     from /home/flo/bin/test.rb:421:in `pgpsign'
     from /home/flo/bin/test.rb:410:in `msg'
     from /home/flo/bin/test.rb:578
     from /home/flo/bin/test.rb:574:in `each'
     from /home/flo/bin/test.rb:574
  gpg: [stdout]: write error: Broken pipe
  gpg: iobuf_flush failed on close: file write error

What's up with that? Any ideas? Why do I get an exception, if I use
begin/rescue and why does gpg say broken pipe? Is there any easier
way to do what I want? I am sorry if this is a bit off-topic,
I know it feels more like a general misunderstanding of pipes than
a ruby specific problem.

Thanks in advance,
Flo