def interupter(): if sys.platform == 'win32': import win32api win32api.GenerateConsoleCtrlEvent(0, 0) else: import signal os.kill(os.getpid(), signal.SIGINT)
def do_terminate(self): assert self.hProcess is not None assert self.hThread is not None start = default_timer() logging.debug("ATTEMPT at termination") graceful = True if graceful: logging.debug("### send Ctrl+C") # avoid terminating our process win32api.SetConsoleCtrlHandler(None, True) win32api.GenerateConsoleCtrlEvent(win32console.CTRL_C_EVENT, self.pid) else: win32api.TerminateProcess(self.hProcess, 15) self.post_terminate() logging.debug("POST terminate DONE") # If the HandlerRoutine parameter is NULL, a # TRUE value causes the calling process to ignore CTRL+C input, and a # FALSE value restores normal processing of CTRL+C input. This attribute of ignoring or processing CTRL+C is inherited by child processes. # # HAS TO BE called AFTER process has been terminated win32api.SetConsoleCtrlHandler(None, False) diff = default_timer() - start logger.debug("Termination took: %.4f" % diff) logging.debug("TERMINATE OVER")
def stop(self): try: self.log('Stopping nio process') if self.process: win32api.GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, self.process.pid) self.log('CTRL_BREAK_EVENT sent') except Exception as e: self.error('Exception stopping: {}'.format(e))
def stop(self): # Send Ctrl-C to sox and ignore it in this script. try: sys.stderr.write("SoxRecorder: sending ctrl-c to sox\n") sys.stderr.flush() win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0) sys.stderr.write("SoxRecorder: sent ctrl-c to sox\n") sys.stderr.flush() except KeyboardInterrupt: sys.stderr.write("SoxRecorder: passing on keyboardinterrupt\n") sys.stderr.flush() pass self._rec_proc.communicate() return None
def kill_rec(rec_proc): # Send Ctrl-C to sox and ignore it in this script. try: sys.stderr.write("ultrasession: sending ctrl-c to sox\n") sys.stderr.flush() win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0) sys.stderr.write("ultrasession: sent ctrl-c to sox\n") sys.stderr.flush() except KeyboardInterrupt: sys.stderr.write("ultrasession: passing on keyboardinterrupt\n") sys.stderr.flush() pass rec_proc.communicate() return None
def __close_internal_windows(self): self.log.debug("Sending CTRL_C_EVENT to chromium") win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, self.cr_proc.pid) self.cr_proc.send_signal(signal.CTRL_BREAK_EVENT) self.cr_proc.send_signal(signal.CTRL_C_EVENT) self.cr_proc.send_signal(1) self.log.debug("Sent") try: self.check_process_ded( ) # Needed to flush the communcation pipes, sometimes # I can't get this to f*****g ever work, # so just skip and go straight to termination. # self.log.debug("Waiting for chromium to exit") # try: # self.cr_proc.wait(timeout=5) # except subprocess.TimeoutExpired: # pass try: self.cr_proc.terminate() except ProcessLookupError: self.log.debug( "Process exited normally, no need to terminate.") self.check_process_ded( ) # Processes may dangle until the pipes are closed. try: self.cr_proc.kill() except ProcessLookupError: self.log.debug( "Process exited normally, no need to terminate.") self.check_process_ded( ) # Processes may dangle until the pipes are closed. except cr_exceptions.ChromeDiedError: self.log.debug( "ChromeDiedError while polling. Ignoring due to shutdown.") # Considering we're /trying/ to kill chrome, it # dying is OK. self.log.debug("Pid: %s, Return code: %s", self.cr_proc.pid, self.cr_proc.returncode) self.log.debug("Chromium closed!")
def execute(self, cmd): (name, cmd) = cmd.split(self.SEP) self.logger.warn("[%s] Running \"%s\"" % (name, cmd)) if self.procs.get(name): if cmd != "QUIT": print "Process already running!" else: #self.procs[name].shutdown() # Only works in linux try: print "TODO: Graceful shutdown" # This doesn't work. win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0) self.procs[name].proc.wait() except KeyboardInterrupt: print "ignoring ctrl c" self.procs[name].join() del self.procs[name] else: if cmd == "QUIT": print "Process wasn't started!" else: self.procs[name] = ProcessMonitor(cmd, auto_restart=False) self.procs[name].start()
def __close_internal_windows(self): ''' Shut down the chrome process. On linux, this will emit a CTRL+C event to the process if chrome does not shut down within the timeout (5 seconds). ''' self.log.debug("Sending CTRL_C_EVENT to chromium") try: win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, self.cr_proc.pid) self.cr_proc.send_signal(signal.CTRL_BREAK_EVENT) self.cr_proc.send_signal(signal.CTRL_C_EVENT) self.cr_proc.send_signal(1) except (OSError, SystemError, pywintypes.error) as e: # Ignore "invalid handle" errors, probably caused by running without a shell # (e.g. in pyinstaller frozen bundle with --noconsole). if 6 == getattr(e, "winerror", getattr(e.__cause__, "winerror", -1)): self.log.debug( "Sending signal failed; attempting termination.") else: raise else: self.log.debug("Sent") try: self._check_process_dead( ) # Needed to flush the communcation pipes, sometimes # I can't get this to f*****g ever work, # so just skip and go straight to termination. # self.log.debug("Waiting for chromium to exit") # try: # self.cr_proc.wait(timeout=5) # except subprocess.TimeoutExpired: # pass try: self.cr_proc.terminate() except ProcessLookupError: self.log.debug( "Process exited normally, no need to terminate.") self._check_process_dead( ) # Processes may dangle until the pipes are closed. try: self.cr_proc.kill() except ProcessLookupError: self.log.debug( "Process exited normally, no need to terminate.") self._check_process_dead( ) # Processes may dangle until the pipes are closed. except cr_exceptions.ChromeDiedError: self.log.debug( "ChromeDiedError while polling. Ignoring due to shutdown.") # Considering we're /trying/ to kill chrome, it # dying is OK. self.log.debug("Pid: %s, Return code: %s", self.cr_proc.pid, self.cr_proc.returncode) self.log.debug("Chromium closed!")
stdout=stdout, stderr=stderr) LOG.info('Job [%s] DONE' % (self.session_id)) self._yield_reply(StatusCodes.FINISHED, run_as, job_result) except Exception, ex: LOG.error(ex) finally: processor.clean() self._close() # Invoke clean if os.name == 'nt': import win32api import win32con win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0) else: os.kill(os.getpid(), signal.SIGHUP) def ack(self, *args): LOG.info("Session::%s :: ACK" % self.session_id) self._close() def err(self, *args): LOG.info("Session::%s :: ERR:: %s" % (self.session_id, args)) self._close() def target_match(self, job): if self.matcher.is_match(job.targets): try: session = AgentNode.Session(job.job_id, self.backend)
def run(self): global terminate # Open server socket self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.bind((HOST, PORT)) while not terminate: # Listen server socket self.s.listen(1) conn, addr = self.s.accept() while not terminate: l = 0 lstr = '' # Read length first, it comes in 4 bytes try: lstr = stream2str(conn.recv(4)) if len(lstr) <= 0: break except: traceback.print_exc() break if terminate: break l = ord(lstr[0]) + (ord(lstr[1]) << 8) + ( ord(lstr[2]) << 16) + (ord(lstr[3]) << 24) if l > 0: # Valid length received, now wait for the message try: # Read the message itself received = '' while len(received) < l: r = stream2str(conn.recv(l)) if len(r) == 0: break received = received + r if len(received) < l: break except: traceback.print_exc() break if len(received) >= 7 and received[0:7] == 'SLIMV::': command = received[7:] if len(command) >= 9 and command[0:9] == 'INTERRUPT': try: if mswindows: import win32api CTRL_C_EVENT = 0 win32api.GenerateConsoleCtrlEvent( CTRL_C_EVENT, 0) else: import signal os.kill(self.pid, signal.SIGINT) except: # OK, at least we tried # Go on without interruption pass if len(command) >= 8 and command[0:8] == 'OUTPUT::': output_filename = command[8:].rstrip('\n') self.buffer.setfile(output_filename) else: # Fork here: write message to the stdin of REPL # and also write it to the display (display queue buffer) self.buffer.writebegin() self.buffer.write_nolock(received) os.write(self.inp.fileno(), str2stream(received)) self.buffer.writeend() conn.close()
def sigint(self): try: import win32api, win32con win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, self.pid) except: pass