Class: Async::Signals::Controller

Inherits:
Object
  • Object
show all
Defined in:
lib/async/signals/controller.rb

Overview

Coordinates process-wide signal handlers for multiple consumers.

Defined Under Namespace

Classes: Registration, State

Instance Method Summary collapse

Constructor Details

#initializeController

Initialize the controller.



110
111
112
113
114
# File 'lib/async/signals/controller.rb', line 110

def initialize
	@mutex = ::Thread::Mutex.new
	@states = {}
	@dispatch = {}.freeze
end

Instance Method Details

#dispatch(signal) ⇒ Object

Dispatch a signal to all currently active handlers.



145
146
147
148
149
150
151
# File 'lib/async/signals/controller.rb', line 145

def dispatch(signal)
	number = ::Signal.list.fetch(signal)
	
	@dispatch[signal]&.each do |handler, context|
		handler.call(number, context)
	end
end

#install(handlers) ⇒ Object

Install signal handlers.



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/async/signals/controller.rb', line 120

def install(handlers)
	installed_handlers = handlers.to_h.freeze
	registration = Registration.new(self, installed_handlers)
	
	@mutex.synchronize do
		installed_handlers.each do |signal, handler|
			add(signal, registration, handler)
		end
		
		update_dispatch
	end
	
	if block_given?
		begin
			return yield handlers
		ensure
			registration.close
		end
	else
		return registration
	end
end

#remove(registration, handlers) ⇒ Object

Remove a set of installed handlers.



156
157
158
159
160
161
162
163
164
# File 'lib/async/signals/controller.rb', line 156

def remove(registration, handlers)
	@mutex.synchronize do
		handlers.each_key do |signal|
			remove_signal(signal, registration)
		end
		
		update_dispatch
	end
end

#reset!Object

Reset all installed signal handlers to their previous signal traps.



167
168
169
170
171
172
173
174
175
176
# File 'lib/async/signals/controller.rb', line 167

def reset!
	@mutex.synchronize do
		@states.each do |signal, state|
			::Signal.trap(signal, state.previous)
		end
		
		@states.clear
		update_dispatch
	end
end