Class: SafeTimeout::InterruptingChildProcess
- Inherits:
-
Object
- Object
- SafeTimeout::InterruptingChildProcess
- Defined in:
- lib/safe_timeout/interrupting_child_process.rb
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ InterruptingChildProcess
constructor
A new instance of InterruptingChildProcess.
- #start(&block) ⇒ Object
- #stop ⇒ Object
- #wait_for_expiration ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ InterruptingChildProcess
Returns a new instance of InterruptingChildProcess.
4 5 6 7 |
# File 'lib/safe_timeout/interrupting_child_process.rb', line 4 def initialize(={}) @expiration = Time.now.to_f + .fetch(:timeout) @on_timeout = .fetch(:on_timeout) end |
Instance Method Details
#start(&block) ⇒ Object
9 10 11 12 13 14 15 |
# File 'lib/safe_timeout/interrupting_child_process.rb', line 9 def start(&block) Signal.trap("TRAP", &@on_timeout) Kernel.fork { wait_for_expiration } yield ensure stop rescue nil end |
#stop ⇒ Object
17 18 19 20 |
# File 'lib/safe_timeout/interrupting_child_process.rb', line 17 def stop # Tell that child to stop interrupting! Process.kill("HUP", @child_pid) end |
#wait_for_expiration ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/safe_timeout/interrupting_child_process.rb', line 22 def wait_for_expiration Signal.trap("HUP") { exit 0 } # If the parent dies unexpectedly and the child is never told to # stop, it becomes an orphan and is given to the init process (1) # or worse yet it becomes a zombie with parent 0. In either case, # stop interrupting! while Process.ppid > 1 sleep 0.1 if Time.now.to_f > @expiration Process.kill("TRAP", Process.ppid) return end end end |