def init_signals(self):
# reset signaling
[signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS]
# init new signaling
signal.signal(signal.SIGQUIT, self.handle_quit)
signal.signal(signal.SIGTERM, self.handle_exit)
signal.signal(signal.SIGINT, self.handle_quit)
signal.signal(signal.SIGWINCH, self.handle_winch)
signal.signal(signal.SIGUSR1, self.handle_usr1)
signal.signal(signal.SIGABRT, self.handle_abort)
# Don't let SIGTERM and SIGUSR1 disturb active requests
# by interrupting system calls
if hasattr(signal, 'siginterrupt'): # python >= 2.6
signal.siginterrupt(signal.SIGTERM, False)
signal.siginterrupt(signal.SIGUSR1, False)
python类SIGQUIT的实例源码
def _KillWebServers():
for s in [signal.SIGTERM, signal.SIGINT, signal.SIGQUIT, signal.SIGKILL]:
signalled = []
for server in ['lighttpd', 'webpagereplay']:
for p in psutil.process_iter():
try:
if not server in ' '.join(p.cmdline):
continue
logging.info('Killing %s %s %s', s, server, p.pid)
p.send_signal(s)
signalled.append(p)
except Exception as e:
logging.warning('Failed killing %s %s %s', server, p.pid, e)
for p in signalled:
try:
p.wait(1)
except Exception as e:
logging.warning('Failed waiting for %s to die. %s', p.pid, e)
def KillAllAdb():
def GetAllAdb():
for p in psutil.process_iter():
try:
if 'adb' in p.name:
yield p
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
for sig in [signal.SIGTERM, signal.SIGQUIT, signal.SIGKILL]:
for p in GetAllAdb():
try:
logging.info('kill %d %d (%s [%s])', sig, p.pid, p.name,
' '.join(p.cmdline))
p.send_signal(sig)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
for p in GetAllAdb():
try:
logging.error('Unable to kill %d (%s [%s])', p.pid, p.name,
' '.join(p.cmdline))
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
def stop(self, graceful=True):
"""\
Stop workers
:attr graceful: boolean, If True (the default) workers will be
killed gracefully (ie. trying to wait for the current connection)
"""
unlink = self.reexec_pid == self.master_pid == 0 and not self.systemd
sock.close_sockets(self.LISTENERS, unlink)
self.LISTENERS = []
sig = signal.SIGTERM
if not graceful:
sig = signal.SIGQUIT
limit = time.time() + self.cfg.graceful_timeout
# instruct the workers to exit
self.kill_workers(sig)
# wait until the graceful timeout
while self.WORKERS and time.time() < limit:
time.sleep(0.1)
self.kill_workers(signal.SIGKILL)
def init_signals(self):
# Set up signals through the event loop API.
self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit,
signal.SIGQUIT, None)
self.loop.add_signal_handler(signal.SIGTERM, self.handle_exit,
signal.SIGTERM, None)
self.loop.add_signal_handler(signal.SIGINT, self.handle_quit,
signal.SIGINT, None)
self.loop.add_signal_handler(signal.SIGWINCH, self.handle_winch,
signal.SIGWINCH, None)
self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1,
signal.SIGUSR1, None)
self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort,
signal.SIGABRT, None)
# Don't let SIGTERM and SIGUSR1 disturb active requests
# by interrupting system calls
signal.siginterrupt(signal.SIGTERM, False)
signal.siginterrupt(signal.SIGUSR1, False)
def stop(self, graceful=True):
"""\
Stop workers
:attr graceful: boolean, If True (the default) workers will be
killed gracefully (ie. trying to wait for the current connection)
"""
if self.reexec_pid == 0 and self.master_pid == 0:
for l in self.LISTENERS:
l.close()
self.LISTENERS = []
sig = signal.SIGTERM
if not graceful:
sig = signal.SIGQUIT
limit = time.time() + self.cfg.graceful_timeout
# instruct the workers to exit
self.kill_workers(sig)
# wait until the graceful timeout
while self.WORKERS and time.time() < limit:
time.sleep(0.1)
self.kill_workers(signal.SIGKILL)
def stop(self, graceful=True):
"""\
Stop workers
:attr graceful: boolean, If True (the default) workers will be
killed gracefully (ie. trying to wait for the current connection)
"""
self.LISTENERS = []
sig = signal.SIGTERM
if not graceful:
sig = signal.SIGQUIT
limit = time.time() + self.cfg.graceful_timeout
# instruct the workers to exit
self.kill_workers(sig)
# wait until the graceful timeout
while self.WORKERS and time.time() < limit:
time.sleep(0.1)
self.kill_workers(signal.SIGKILL)
def init_signals(self):
# reset signaling
[signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS]
# init new signaling
signal.signal(signal.SIGQUIT, self.handle_quit)
signal.signal(signal.SIGTERM, self.handle_exit)
signal.signal(signal.SIGINT, self.handle_quit)
signal.signal(signal.SIGWINCH, self.handle_winch)
signal.signal(signal.SIGUSR1, self.handle_usr1)
signal.signal(signal.SIGABRT, self.handle_abort)
# Don't let SIGTERM and SIGUSR1 disturb active requests
# by interrupting system calls
if hasattr(signal, 'siginterrupt'): # python >= 2.6
signal.siginterrupt(signal.SIGTERM, False)
signal.siginterrupt(signal.SIGUSR1, False)
def test__terminates_with_kill_and_killpg(self):
protocol = SignalPrinterProtocol()
process = yield self.startSignalPrinter(protocol, pgrp=True)
# Capture the pid now; it gets cleared when the process exits.
pid = process.pid
# Terminate and wait for it to exit.
self.terminateSignalPrinter(process, protocol)
yield protocol.done.addErrback(suppress, ProcessTerminated)
# os.kill was called once then os.killpg was called twice because the
# subprocess made itself a process group leader.
self.assertThat(
twisted_module._os_kill, MockCallsMatch(
mock.call(pid, signal.SIGTERM),
))
self.assertThat(
twisted_module._os_killpg, MockCallsMatch(
mock.call(pid, signal.SIGQUIT),
mock.call(pid, signal.SIGKILL),
))
def test__terminates_with_kill_if_not_in_separate_process_group(self):
protocol = SignalPrinterProtocol()
process = yield self.startSignalPrinter(protocol, pgrp=False)
# Capture the pid now; it gets cleared when the process exits.
pid = process.pid
# Terminate and wait for it to exit.
self.terminateSignalPrinter(process, protocol)
yield protocol.done.addErrback(suppress, ProcessTerminated)
# os.kill was called 3 times because the subprocess did not make
# itself a process group leader.
self.assertThat(
twisted_module._os_kill, MockCallsMatch(
mock.call(pid, signal.SIGTERM),
mock.call(pid, signal.SIGQUIT),
mock.call(pid, signal.SIGKILL),
))
self.assertThat(
twisted_module._os_killpg, MockNotCalled())
def cli(log_level, live):
logging.basicConfig(
filename='arbloop.log',
format='[%(asctime)s] [%(levelname)s] %(message)s',
level=log_level
)
logging.info('Warming up traders ...')
gevent.signal(signal.SIGQUIT, gevent.kill)
workers = []
for product in config.TRADER_PRODUCTS or []:
trader = Trader(product=product, live=live)
workers.append(
gevent.spawn(trader.trade)
)
gevent.joinall(workers)
def stop(self, graceful=True):
"""\
Stop workers
:attr graceful: boolean, If True (the default) workers will be
killed gracefully (ie. trying to wait for the current connection)
"""
if self.reexec_pid == 0 and self.master_pid == 0:
for l in self.LISTENERS:
l.close()
self.LISTENERS = []
sig = signal.SIGTERM
if not graceful:
sig = signal.SIGQUIT
limit = time.time() + self.cfg.graceful_timeout
# instruct the workers to exit
self.kill_workers(sig)
# wait until the graceful timeout
while self.WORKERS and time.time() < limit:
time.sleep(0.1)
self.kill_workers(signal.SIGKILL)
def init_signals(self):
# Set up signals through the event loop API.
self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit,
signal.SIGQUIT, None)
self.loop.add_signal_handler(signal.SIGTERM, self.handle_exit,
signal.SIGTERM, None)
self.loop.add_signal_handler(signal.SIGINT, self.handle_quit,
signal.SIGINT, None)
self.loop.add_signal_handler(signal.SIGWINCH, self.handle_winch,
signal.SIGWINCH, None)
self.loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1,
signal.SIGUSR1, None)
self.loop.add_signal_handler(signal.SIGABRT, self.handle_abort,
signal.SIGABRT, None)
# Don't let SIGTERM and SIGUSR1 disturb active requests
# by interrupting system calls
signal.siginterrupt(signal.SIGTERM, False)
signal.siginterrupt(signal.SIGUSR1, False)
def __init__(self, settings=None, hooks=None, *args, **kwargs):
"""
Initialize the NNTPManager() based on the provided settings.
it is presumed settings is a loaded NNTPSettings() object.
"""
# A connection pool of NNTPConnections
self._pool = []
# A mapping of active worker threads
self._workers = []
# Keep track of the workers available for processing
# we will use this value to determine if we need to spin
# up another process or not.
self._work_tracker = WorkTracker()
# Queue Control
self._work_queue = Queue()
# Map signal
gevent.signal(signal.SIGQUIT, gevent.kill)
# Define our hooks (if any)
self.hooks = HookManager()
if hooks:
self.hooks.add(hooks=hooks)
if settings is None:
# Use defaults
settings = NNTPSettings()
if not len(settings.nntp_servers):
logger.warning("There were no NNTP Servers defined to load.")
raise AttributeError('No NNTP Servers Defined')
# Store our defined settings
self._settings = settings
return
def test_EventAppPortConnectionSIGQUITNoPersist(self):
self.localEvent = threading.Event()
self.eventFlag = False
self._nb_domMgr, domMgr = self.launchDomainManager("--nopersist", endpoint="giop:tcp::5679", dbURI=self._dbfile)
self._nb_devMgr, devMgr = self.launchDeviceManager("/nodes/test_EventPortTestDevice_node/DeviceManager.dcd.xml")
domainName = scatest.getTestDomainName()
domMgr.installApplication("/waveforms/PortConnectFindByDomainFinderEvent/PortConnectFindByDomainFinderEvent.sad.xml")
appFact = domMgr._get_applicationFactories()[0]
app = appFact.create(appFact._get_name(), [], [])
app.start()
# Kill the domainMgr
os.kill(self._nb_domMgr.pid, signal.SIGQUIT)
if not self.waitTermination(self._nb_domMgr, 5.0):
self.fail("Domain Manager Failed to Die")
# Restart the Domain Manager (which should restore the old channel)
self._nb_domMgr, domMgr = self.launchDomainManager("--nopersist", endpoint="giop:tcp::5679", dbURI=self._dbfile)
newappFact = domMgr._get_applicationFactories()
self.assertEqual(len(newappFact), 0)
apps = domMgr._get_applications()
self.assertEqual(len(apps), 0)
devMgrs = domMgr._get_deviceManagers()
self.assertEqual(len(devMgrs), 0)
def set_graceful_exit():
"""
Set up a graceful exit when certain signals arrive.
"""
for sig in [signal.SIGHUP,
signal.SIGINT,
signal.SIGQUIT,
signal.SIGTERM]:
signal.signal(sig, __exit_handler)
def _register_signals(self):
for SIG in [signal.SIGINT, signal.SIGTERM, signal.SIGQUIT, signal.SIGHUP]:
self.register_shutdown_signal(SIG)
def handle_quit(self):
"SIGQUIT handling"
self.stop(False)
raise StopIteration
def shutdown_on_signals(self, signals=None):
if signals is None:
signals = [signal.SIGHUP,
signal.SIGINT,
signal.SIGQUIT,
signal.SIGTERM,
signal.SIGTSTP]
for sig in signals:
signal.signal(sig, self._handle_signal_shutdown)
def init_signals(self):
# Set up signals through the event loop API.
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGQUIT, self.handle_quit,
signal.SIGQUIT, None)
loop.add_signal_handler(signal.SIGTERM, self.handle_exit,
signal.SIGTERM, None)
loop.add_signal_handler(signal.SIGINT, self.handle_quit,
signal.SIGINT, None)
loop.add_signal_handler(signal.SIGWINCH, self.handle_winch,
signal.SIGWINCH, None)
loop.add_signal_handler(signal.SIGUSR1, self.handle_usr1,
signal.SIGUSR1, None)
loop.add_signal_handler(signal.SIGABRT, self.handle_abort,
signal.SIGABRT, None)
# Don't let SIGTERM and SIGUSR1 disturb active requests
# by interrupting system calls
signal.siginterrupt(signal.SIGTERM, False)
signal.siginterrupt(signal.SIGUSR1, False)