def kas(argv):
"""
The main entry point of kas.
"""
create_logger()
parser = kas_get_argparser()
args = parser.parse_args(argv)
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
logging.info('%s %s started', os.path.basename(sys.argv[0]), __version__)
loop = asyncio.get_event_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, interruption)
atexit.register(_atexit_handler)
for plugin in getattr(kasplugin, 'plugins', []):
if plugin().run(args):
return
parser.print_help()
python类SIGINT的实例源码
def set_zombie_refresh_to_fail(self, refresh_job):
current_pid = refresh_job.pid
if current_pid is None:
return
p = psutil.Process(current_pid)
if p.status() != psutil.STATUS_ZOMBIE:
return
refresh = self.schematizer.get_refresh_by_id(
refresh_job.refresh_id
)
if refresh.status == RefreshStatus.IN_PROGRESS:
# Must update manually (not relying on the signal),
# as the process may not properly handle the signal
# if it's a zombie
self.schematizer.update_refresh(
refresh_id=refresh_job.refresh_id,
status=RefreshStatus.FAILED,
offset=0
)
source = refresh_job.source
del self.active_refresh_jobs[source]
os.kill(current_pid, signal.SIGINT)
def run(self):
"""Option to calling manually calling start()/stop(). This will start
the server and watch for signals to stop the server"""
self.server.start()
log.info(" ABCIServer started on port: {}".format(self.port))
# wait for interrupt
evt = Event()
gevent.signal(signal.SIGQUIT, evt.set)
gevent.signal(signal.SIGTERM, evt.set)
gevent.signal(signal.SIGINT, evt.set)
evt.wait()
log.info("Shutting down server")
self.server.stop()
# TM will spawn off 3 connections: mempool, consensus, query
# If an error happens in 1 it still leaves the others open which
# means you don't have all the connections available to TM
def test_NSCleanup(self):
domain_name = self._domMgr._get_name()
ns_domMgr = URI.stringToName("%s/%s" % (domain_name, domain_name))
ns_domMgrCtx = URI.stringToName("%s" % (domain_name))
ns_ODM = URI.stringToName("%s/%s" % (domain_name, "ODM_Channel"))
ns_IDM = URI.stringToName("%s/%s" % (domain_name, "IDM_Channel"))
domCtx_ref = self._root.resolve(ns_domMgrCtx)
domMgr_ref = self._root.resolve(ns_domMgr)
ODM_ref = self._root.resolve(ns_ODM)
IDM_ref = self._root.resolve(ns_IDM)
self.assertNotEqual(domCtx_ref, None)
self.assertNotEqual(domMgr_ref, None)
self.assertNotEqual(ODM_ref, None)
self.assertNotEqual(IDM_ref, None)
os.kill(self._domainBooter.pid, signal.SIGINT)
self.waitTermination(self._domainBooter)
self.assertRaises(CosNaming.NamingContext.NotFound, self._root.resolve, ns_domMgrCtx)
def terminateChild(self, child, signals=(signal.SIGINT, signal.SIGTERM)):
if child.poll() != None:
return
try:
#self.waitTermination(child)
for sig in signals:
#print "sending signal " + str(sig) + " to pid:" + str(child.pid)
os.kill(child.pid, sig)
if self.waitTermination(child):
break
child.wait()
except OSError, e:
#print "terminateChild: pid:" + str(child.pid) + " OS ERROR:" + str(e)
pass
finally:
pass
def input(s, stdout = True, timeout = 2,
prompt = rgx2nd(('(.+)', 'py3to2 server: \\1'), ),
subprompt = rgx2nd(('>>> ', '', None), ),
fndexc = re.compile('\WTraceback '),
):
self = _server
if not s: return
SERVER.stdin.write(s)
try:
buf = ''
SERVER.stdin.write("\n\nimport os, signal; os.kill(CLIENTPID, signal.SIGINT)\n")
time.sleep(timeout)
raise IOError('py3to2 server not responding to input: %s'%repr(s))
except KeyboardInterrupt:
buf = os.read(SERVERIO[0], self.bufsize)
buf = subprompt.sub(buf)
if prompt: buf = prompt.sub(buf)
if fndexc.search(buf): raise IOError('py3to2 server input: %s\n%s'%(s, buf))
if stdout: sys.stdout.write(buf)
else: return buf
def input(s, stdout = True, timeout = 2,
prompt = rgx2nd(('(.+)', 'py3to2 server: \\1'), ),
subprompt = rgx2nd(('>>> ', '', None), ),
fndexc = re.compile('\WTraceback '),
):
self = _server
if not s: return
SERVER.stdin.write(s)
try:
buf = ''
SERVER.stdin.write("\n\nimport os, signal; os.kill(CLIENTPID, signal.SIGINT)\n")
time.sleep(timeout)
raise IOError('py3to2 server not responding to input: %s'%repr(s))
except KeyboardInterrupt:
buf = os.read(SERVERIO[0], self.bufsize)
buf = subprompt.sub(buf)
if prompt: buf = prompt.sub(buf)
if fndexc.search(buf): raise IOError('py3to2 server input: %s\n%s'%(s, buf))
if stdout: sys.stdout.write(buf)
else: return buf
def cleanup(self):
print
if (self.webserver is not None):
if (self.config["daemon_web"]):
self.display.alert("Webserver is still running as requested.")
else:
# send SIGTERM to the web process
self.display.output("stopping the webserver")
self.webserver.send_signal(signal.SIGINT)
# delete the pid file
os.remove(self.pid_path + "spfwebsrv.pid")
# as a double check, manually kill the process
self.killProcess(self.webserverpid)
# call report generation
self.generateReport()
# exit
sys.exit(0)
#----------------------------
# Kill specified process
#----------------------------
def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
"""
Blocks until one of the signals are received and stops the updater
Args:
stop_signals: Iterable containing signals from the signal module
that should be subscribed to. Updater.stop() will be called on
receiving one of those signals. Defaults to (SIGINT, SIGTERM,
SIGABRT)
"""
for sig in stop_signals:
signal(sig, self.signal_handler)
self.is_idle = True
while self.is_idle:
sleep(1)
def __init__(self, task_name, manager, config, timer, base_dir, backup_dir, **kwargs):
self.task_name = task_name
self.manager = manager
self.config = config
self.timer = timer
self.base_dir = base_dir
self.backup_dir = backup_dir
self.args = kwargs
self.verbose = self.config.verbose
self.runnning = False
self.stopped = False
self.completed = False
self.exit_code = 255
self.thread_count = None
self.cpu_count = cpu_count()
self.compression_method = 'none'
self.compression_supported = ['none']
self.timer_name = self.__class__.__name__
signal(SIGINT, SIG_IGN)
signal(SIGTERM, self.close)
def testInterruptCaught(self):
default_handler = signal.getsignal(signal.SIGINT)
result = unittest.TestResult()
unittest.installHandler()
unittest.registerResult(result)
self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)
def test(result):
pid = os.getpid()
os.kill(pid, signal.SIGINT)
result.breakCaught = True
self.assertTrue(result.shouldStop)
try:
test(result)
except KeyboardInterrupt:
self.fail("KeyboardInterrupt not handled")
self.assertTrue(result.breakCaught)
def testSecondInterrupt(self):
# Can't use skipIf decorator because the signal handler may have
# been changed after defining this method.
if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
self.skipTest("test requires SIGINT to not be ignored")
result = unittest.TestResult()
unittest.installHandler()
unittest.registerResult(result)
def test(result):
pid = os.getpid()
os.kill(pid, signal.SIGINT)
result.breakCaught = True
self.assertTrue(result.shouldStop)
os.kill(pid, signal.SIGINT)
self.fail("Second KeyboardInterrupt not raised")
try:
test(result)
except KeyboardInterrupt:
pass
else:
self.fail("Second KeyboardInterrupt not raised")
self.assertTrue(result.breakCaught)
def testHandlerReplacedButCalled(self):
# Can't use skipIf decorator because the signal handler may have
# been changed after defining this method.
if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
self.skipTest("test requires SIGINT to not be ignored")
# If our handler has been replaced (is no longer installed) but is
# called by the *new* handler, then it isn't safe to delay the
# SIGINT and we should immediately delegate to the default handler
unittest.installHandler()
handler = signal.getsignal(signal.SIGINT)
def new_handler(frame, signum):
handler(frame, signum)
signal.signal(signal.SIGINT, new_handler)
try:
pid = os.getpid()
os.kill(pid, signal.SIGINT)
except KeyboardInterrupt:
pass
else:
self.fail("replaced but delegated handler doesn't raise interrupt")
def testRemoveResult(self):
result = unittest.TestResult()
unittest.registerResult(result)
unittest.installHandler()
self.assertTrue(unittest.removeResult(result))
# Should this raise an error instead?
self.assertFalse(unittest.removeResult(unittest.TestResult()))
try:
pid = os.getpid()
os.kill(pid, signal.SIGINT)
except KeyboardInterrupt:
pass
self.assertFalse(result.shouldStop)
def prompt(cleanup_function, signalnum=signal.SIGINT):
"""Give the user a decision prompt when ctrl+C is pressed."""
def cleanup_prompt(signum, frame):
# This handler is not re-entrant.
# Allow the user to exit immediately by sending the same signal
# a second time while in this block.
with handle(signalnum, sysexit):
choice = input(dedent("""
You pressed ctrl+C. What would you like to do?
- to exit immediately, press ctrl+C again
- to clean up and exit gracefully, enter 'c' or 'cleanup'
- to resume operation, press enter
(cleanup?): """))
if choice and 'cleanup'.casefold().startswith(choice.casefold()):
print('Cleaning up...')
cleanup_function()
print('Done cleaning up; exiting.')
sys.exit(1)
print('Continuing...')
return cleanup_prompt
def testInterruptCaught(self):
default_handler = signal.getsignal(signal.SIGINT)
result = unittest2.TestResult()
unittest2.installHandler()
unittest2.registerResult(result)
self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)
def test(result):
pid = os.getpid()
os.kill(pid, signal.SIGINT)
result.breakCaught = True
self.assertTrue(result.shouldStop)
try:
test(result)
except KeyboardInterrupt:
self.fail("KeyboardInterrupt not handled")
self.assertTrue(result.breakCaught)
def testSecondInterrupt(self):
# Can't use skipIf decorator because the signal handler may have
# been changed after defining this method.
if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
self.skipTest("test requires SIGINT to not be ignored")
result = unittest2.TestResult()
unittest2.installHandler()
unittest2.registerResult(result)
def test(result):
pid = os.getpid()
os.kill(pid, signal.SIGINT)
result.breakCaught = True
self.assertTrue(result.shouldStop)
os.kill(pid, signal.SIGINT)
self.fail("Second KeyboardInterrupt not raised")
try:
test(result)
except KeyboardInterrupt:
pass
else:
self.fail("Second KeyboardInterrupt not raised")
self.assertTrue(result.breakCaught)
def testHandlerReplacedButCalled(self):
# Can't use skipIf decorator because the signal handler may have
# been changed after defining this method.
if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
self.skipTest("test requires SIGINT to not be ignored")
# If our handler has been replaced (is no longer installed) but is
# called by the *new* handler, then it isn't safe to delay the
# SIGINT and we should immediately delegate to the default handler
unittest2.installHandler()
handler = signal.getsignal(signal.SIGINT)
def new_handler(frame, signum):
handler(frame, signum)
signal.signal(signal.SIGINT, new_handler)
try:
pid = os.getpid()
os.kill(pid, signal.SIGINT)
except KeyboardInterrupt:
pass
else:
self.fail("replaced but delegated handler doesn't raise interrupt")
def testRemoveResult(self):
result = unittest2.TestResult()
unittest2.registerResult(result)
unittest2.installHandler()
self.assertTrue(unittest2.removeResult(result))
# Should this raise an error instead?
self.assertFalse(unittest2.removeResult(unittest2.TestResult()))
try:
pid = os.getpid()
os.kill(pid, signal.SIGINT)
except KeyboardInterrupt:
pass
self.assertFalse(result.shouldStop)
def test_add_signal_handler_coroutine_error(self, m_signal):
m_signal.NSIG = signal.NSIG
@asyncio.coroutine
def simple_coroutine():
yield from []
# callback must not be a coroutine function
coro_func = simple_coroutine
coro_obj = coro_func()
self.addCleanup(coro_obj.close)
for func in (coro_func, coro_obj):
self.assertRaisesRegex(
TypeError, 'coroutines cannot be used with add_signal_handler',
self.loop.add_signal_handler,
signal.SIGINT, func)
def test_run(udp_server_process):
addr1, addr2 = udp_server_process
forward_addr = ("127.0.0.1", 42353)
argv = ["-p", "%s:%d" % (forward_addr[0], forward_addr[1]),
"-r", "chinadns",
"-u", "%s:%d,%s:%d" %
(addr1[0], addr1[1], addr2[0], addr2[1]),
"-l", "debug",
"-f", "%s/chnroute_test.txt" % (mydir),
"-b", "%s/iplist_test.txt" % (mydir),
"--cache"]
p = Process(target=chinadns.run, args=(argv,))
p.start()
time.sleep(0.5)
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
q = dnslib.DNSRecord.question(qname)
client.sendto(bytes(q.pack()), forward_addr)
data, _ = client.recvfrom(1024)
d = dnslib.DNSRecord.parse(data)
assert str(d.rr[0].rdata) == "101.226.103.106"
client.close()
os.kill(p.pid, signal.SIGINT)
p.join()
def kill(self, sig):
'''Sends a Unix signal to the subprocess.
Use constants from the :mod:`signal` module to specify which signal.
'''
if sys.platform == 'win32':
if sig in [signal.SIGINT, signal.CTRL_C_EVENT]:
sig = signal.CTRL_C_EVENT
elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]:
sig = signal.CTRL_BREAK_EVENT
else:
sig = signal.SIGTERM
os.kill(self.proc.pid, sig)
def signal_handler(signum, *kwargs):
""" A handler for various interrupts
"""
global exit_flag
exit_flag = True
if signum == signal.SIGINT:
print(ERROR + "user quit" + Style.RESET_ALL)
else:
print(ERROR + "signal caught: {}".format(signum) + Style.RESET_ALL)
print("[*] shutting down at {}".format(time.ctime()))
# let time for the threads to terminate
time.sleep(2)
sys.exit(0)
def _build_attributes_validator(mcs):
"""
Returns validator to validate the sub-classes attributes.
"""
valid_attributes = {
Required("commands", 'required class attribute'): [
{
Required("name"): str,
Required("cmd"): [str],
Optional("kill-signal", default=signal.SIGINT): int
}
]
}
for attr_name, class_client in mcs._class_clients.items():
client_validator = {
Required("name"): str,
}
client_validator.update(class_client.validator())
key = Optional(attr_name, 'required class attribute')
valid_attributes[key] = [client_validator]
return Schema(valid_attributes, extra=ALLOW_EXTRA)
def reap_all(self):
"""
Kill, as gently as possible, all processes.
Loop through all processes and try to kill them with
a sequence of :code:`SIGINT`, :code:`SIGTERM` and
:code:`SIGKILL`.
"""
for proc in self._procs:
ret_code = proc.poll()
if ret_code is None:
proc.send_signal(signal.SIGINT)
time.sleep(3)
ret_code = ret_code or proc.poll()
if ret_code is None: # pragma: no coverage
proc.terminate()
time.sleep(3)
ret_code = ret_code or proc.poll() # pragma: no coverage
if ret_code is None: # pragma: no coverage
proc.kill()
def run_foreground(command, env=None):
if DEBUG:
print("DEBUG: Executing {}".format(command))
cmd_env = os.environ.copy()
if env is not None:
cmd_env.update(env)
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, env=cmd_env)
try:
for line in iter(p.stdout.readline, b''):
print(line.rstrip().decode('utf-8'))
# send Ctrl-C to subprocess
except KeyboardInterrupt:
p.send_signal(signal.SIGINT)
for line in iter(p.stdout.readline, b''):
print(line.rstrip().decode('utf-8'))
raise
finally:
p.wait()
return p.returncode
def main():
import signal
rospy.init_node('uwb_multi_range_node')
u = UWBMultiRange()
def sigint_handler(sig, _):
if sig == signal.SIGINT:
u.stop()
signal.signal(signal.SIGINT, sigint_handler)
try:
u.exec_()
except (rospy.ROSInterruptException, select.error):
rospy.logwarn("Interrupted... Stopping.")
def main():
import signal
rospy.init_node('uwb_tracker_node')
u = UWBTracker()
def sigint_handler(sig, _):
if sig == signal.SIGINT:
u.stop()
signal.signal(signal.SIGINT, sigint_handler)
try:
u.exec_()
except (rospy.ROSInterruptException, select.error):
rospy.logwarn("Interrupted... Stopping.")
def __init__(self, *args, **kwargs):
super(SigIntMixin, self).__init__(*args, **kwargs)
signal(SIGINT, self._sigint_handler)
def __init__(self, *args, **kwargs):
"""
Save the original SIGINT handler for later.
"""
super(InterruptibleMixin, self).__init__(*args, **kwargs)
self.original_handler = signal(SIGINT, self.handle_sigint)
# If signal() returns None, the previous handler was not installed from
# Python, and we cannot restore it. This probably should not happen,
# but if it does, we must restore something sensible instead, at least.
# The least bad option should be Python's default SIGINT handler, which
# just raises KeyboardInterrupt.
if self.original_handler is None:
self.original_handler = default_int_handler