Module: Timeout

Defined in:
lib/active_ldap/timeout.rb,
lib/active_ldap/timeout_stub.rb

Class Method Summary collapse

Class Method Details

.alarm(sec, exception = Timeout::Error, &block) ⇒ Object

STUB



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/active_ldap/timeout.rb', line 14

def Timeout.alarm(sec, exception=Timeout::Error, &block)
  return block.call if sec == nil or sec.zero?
 

  # Trap an alarm in case it comes before we're ready
  orig_alrm = trap(:ALRM, 'IGNORE')

  # Setup a fallback in case of a race condition of an
  # alarm before we set the other trap
  trap(:ALRM) do 
    # Don't leave zombies
    Process.wait2()
    # Restore the original handler
    trap('ALRM', orig_alrm)
    # Now raise an exception!
    raise exception, 'execution expired'
  end

  # Spawn the sleeper
  pid = Process.fork {
    begin
      # Sleep x seconds then send SIGALRM 
      sleep(sec)
      # Send alarm!
      Process.kill(:ALRM, Process.ppid)
    end
    exit! 0
  }

  # Setup the real handler
  trap(:ALRM) do
    # Make sure we clean up any zombies
    Process.waitpid(pid)
    # Restore the original handler
    trap(:ALRM, orig_alrm)
    # Now raise an exception!
    raise exception, 'execution expired'
  end

  begin
    # Run the code!
    return block.call
  ensure
    # Restore old alarm handler since we're done
    trap(:ALRM, orig_alrm)
    # Make sure the process is dead
    # This may be run twice (trap occurs during execution) so ignore ESRCH
    Process.kill(:TERM, pid) rescue Errno::ESRCH
    # Don't leave zombies
    Process.waitpid(pid) rescue Errno::ECHILD
  end
end