title: Asynchronous alarm signal
body: <p>I'm looking for a portable interface to POSIX <code>alarm(2)</code> (or similar) in Ruby. That's to say, I would like to be able to set a background timer to send a signal to the current process after <i>n</i> seconds.</p>
  
  <p>I have found some <a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/216201" rel="nofollow noreferrer">good discussion</a> from 2006 on the ruby-talk list that provides a solution using <code>dl/import</code>, but that's a bit of a hack (albeit a neat hack) and not very portable.</p>
  
  <p>I've looked at the much-maligned <code>Timeout</code> module and that won't cut it under JRuby although it works fine with the traditional interpreter. My program is a small command-line shell that uses the Readline library:</p>
  
  <pre><code>TIMEOUT = 5 # seconds
  loop do
    input = nil
    begin
      Timeout.timeout(TIMEOUT) do
        input = Readline::readline('&gt; ', nil)
      end
    rescue Timeout::Error
      puts "Timeout"
      next
    end
    # do something with input
  end
  </code></pre>
  
  <p>Under JRuby it seems the process blocks in the <code>readline</code> call and <code>Timeout::Error</code> is only thrown after (a) the timer expires and (b) the user enters a new line. And the exception doesn't get rescued. Hmm.</p>
  
  <p>So I came up with this workaround:</p>
  
  <pre><code>require 'readline'
  class TimeoutException &lt; Exception ; end
  TIMEOUT = 5 # seconds
  
  loop do
    input = nil
    start_time = Time.now
    thread = Thread.new { input = Readline::readline('&gt; ', nil) }
    begin
      while thread.alive? do
        sleep(1) # prevent CPU from melting
        raise TimeoutException if(Time.now - start_time &gt; TIMEOUT)
      end
    rescue TimeoutException
      thread.exit
      puts "Timeout"
    end
    # do something with input
  end
  </code></pre>
  
  <p>This is... clunky (let's be polite). I just want <code>alarm(2)</code>! I don't really want to drag in non-core libraries (eg Terminator) for this. Is there a better way?</p>
  
  <p>EDIT:
  I can't get another alternative -- creating a thread that sleeps and then sends a signal to the process -- to work  under JRuby either. Does JRuby eat signals? Example:</p>
  
  <pre><code>SIG = 'USR2'
  Signal.trap(SIG) { raise }
  Process.kill(SIG, Process.pid)
  </code></pre>
  
  <p>JRuby simply returns, Ruby returns the expected "unhandled exception" error.</p>