我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用signal.SIGINT。
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()
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 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
def finish(self): """ Restore the original SIGINT handler after finishing. This should happen regardless of whether the progress display finishes normally, or gets interrupted. """ super(InterruptibleMixin, self).finish() signal(SIGINT, self.original_handler)
def handle_sigint(self, signum, frame): """ Call self.finish() before delegating to the original SIGINT handler. This handler should only be in place while the progress display is active. """ self.finish() self.original_handler(signum, frame)
def interruption(): """ Ignore SIGINT/SIGTERM in kas, let them be handled by our sub-processes """ pass
def stop(self): os.kill(self.writer_proc.pid, signal.SIGINT)
def test_RogueService(self): devmgr_nb, devMgr = self.launchDeviceManager("/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml") import ossie.utils.popen as _popen from ossie.utils import redhawk rhdom= redhawk.attach(scatest.getTestDomainName()) serviceName = "fake_1" args = [] args.append("sdr/dev/services/fake/python/fake.py") args.append("DEVICE_MGR_IOR") args.append(self._orb.object_to_string(devMgr)) args.append("SERVICE_NAME") args.append(serviceName) exec_file = "sdr/dev/services/fake/python/fake.py" external_process = _popen.Popen(args, executable=exec_file, cwd=os.getcwd(), preexec_fn=os.setpgrp) time.sleep(2) names=[serviceName] for svc in devMgr._get_registeredServices(): self.assertNotEqual(svc, None) self.assertEqual(svc.serviceName in names, True) for svc in rhdom.services: self.assertNotEqual(svc, None) self.assertEqual(svc._instanceName in names, True) # Kill the external services os.kill(external_process.pid, signal.SIGINT) time.sleep(1) # check rogue service is removed self.assertEquals(len(devMgr._get_registeredServices()), 0) self.assertEquals(len(rhdom.services), 0)
def test_EventAppPortConnectionSIGINT(self): self.localEvent = threading.Event() self.eventFlag = False self._nb_domMgr, domMgr = self.launchDomainManager(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.SIGINT) 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(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 test_nodeBooterDomainNameOverride(self): """Test that we can allow the user to override the domainname with the --domainname argument.""" domainName = scatest.getTestDomainName() domainMgrURI = URI.stringToName("%s/%s" % (domainName, domainName)) # Test that we don't already have a bound domain try: domMgr = self._root.resolve(domainMgrURI) self.assertEqual(domMgr, None) except CosNaming.NamingContext.NotFound: pass # This exception is expected args = ["../../control/framework/nodeBooter","-D", "--domainname", domainName, "-debug", "9","--nopersist" ] nb = Popen(args, cwd=scatest.getSdrPath() ) domMgr = self.waitDomainManager(domainMgrURI) self.assertNotEqual(domMgr, None) # Kill the nodebooter os.kill(nb.pid, signal.SIGINT) self.assertPredicateWithWait(lambda: nb.poll() == 0) # Test that we cleaned up the name; this should be automatic because # the naming context should be empty. try: domMgr = self._root.resolve(domainMgrURI) self.assertEqual(domMgr, None) except CosNaming.NamingContext.NotFound: pass # This exception is expected
def terminateChildrenPidOnly(self, pid, signals=(signal.SIGINT, signal.SIGTERM)): ls = commands.getoutput('ls /proc') entries = ls.split('\n') for entry in entries: filename = '/proc/'+entry+'/status' try: fp = open(filename,'r') stuff = fp.readlines() fp.close() except: continue ret = '' for line in stuff: if 'PPid' in line: ret=line break if ret != '': parentPid = ret.split('\t')[-1][:-1] if parentPid == pid: self.terminateChildrenPidOnly(entry, signals) filename = '/proc/'+pid+'/status' for sig in signals: try: os.kill(int(pid), sig) except: continue done = False attemptCount = 0 while not done: try: fp = open(filename,'r') fp.close() attemptCount += 1 if attemptCount == 10: break time.sleep(0.1) except: done = True if not done: continue
def terminateChildren(self, child, signals=(signal.SIGINT, signal.SIGTERM)): ls = commands.getoutput('ls /proc') entries = ls.split('\n') for entry in entries: filename = '/proc/'+entry+'/status' try: fp = open(filename,'r') stuff = fp.readlines() except: continue for line in stuff: if 'PPid' in line: ret=line break if ret != '': parentPid = int(ret.split('\t')[-1][:-1]) if parentPid == child.pid: self.terminateChildrenPidOnly(entry, signals) if child.poll() != None: return try: for sig in signals: os.kill(child.pid, sig) if self.waitTermination(child): break child.wait() except OSError: pass
def __terminate_process( process, signals=(_signal.SIGINT, _signal.SIGTERM, _signal.SIGKILL) ): if process and process.poll() != None: return try: for sig in signals: _os.kill(process.pid, sig) if __waitTermination(process): break process.wait() except OSError, e: pass finally: pass
def __init__(self): helperBase.__init__(self) self.usesPortIORString = None self._providesPortDict = {} self._processes = {} self._STOP_SIGNALS = ((_signal.SIGINT, 1), (_signal.SIGTERM, 5), (_signal.SIGKILL, None))
def run(*steps): """ Helper to run one or more async functions synchronously, with graceful handling of SIGINT / Ctrl-C. Returns the return value of the last function. """ if not steps: return task = None run._sigint = False # function attr to allow setting from closure loop = asyncio.get_event_loop() def abort(): task.cancel() run._sigint = True added = False try: loop.add_signal_handler(signal.SIGINT, abort) added = True except (ValueError, OSError, RuntimeError) as e: # add_signal_handler doesn't work in a thread if 'main thread' not in str(e): raise try: for step in steps: task = loop.create_task(step) loop.run_until_complete(asyncio.wait([task], loop=loop)) if run._sigint: raise KeyboardInterrupt() if task.exception(): raise task.exception() return task.result() finally: if added: loop.remove_signal_handler(signal.SIGINT)
def _exit_gracefully(self, sig, frame): self.close() if sig == signal.SIGINT: self.original_int_handler(sig, frame) elif sig == signal.SITERM: self.original_term_handler(sig, frame)
def register_signal_handlers(self): self.original_int_handler = signal.getsignal(signal.SIGINT) self.original_term_handler = signal.getsignal(signal.SIGTERM) signal.signal(signal.SIGINT, self._exit_gracefully) signal.signal(signal.SIGTERM, self._exit_gracefully)
def _handle_epoch_interrupt(self, signal_number, frame): # Try to complete the current epoch if user presses CTRL + C logger.warning('Received epoch interrupt signal.' + epoch_interrupt_message) signal.signal(signal.SIGINT, self._handle_batch_interrupt) self.log.current_row['epoch_interrupt_received'] = True # Add a record to the status. Unlike the log record it will be # easy to access at later iterations. self.status['epoch_interrupt_received'] = True
def _restore_signal_handlers(self): signal.signal(signal.SIGINT, self.original_sigint_handler) signal.signal(signal.SIGTERM, self.original_sigterm_handler)