예제 #1
0
    def stop(self, timeout=TIMEOUTS['WaitForProcessStop'], hard=False):
        """Stop a process running. On Windows this is always a hard termination. 
	
		"""
        try:
            with self.__lock:
                if self.exitStatus is not None: return

                try:
                    if self.__job:
                        win32job.TerminateJobObject(self.__job, 0)
                    else:
                        win32process.TerminateProcess(self.__hProcess,
                                                      0)  # pragma: no cover

                except Exception as e:  # pragma: no cover
                    # ignore errors unless the process is still running
                    if win32process.GetExitCodeProcess(
                            self.hProcess) == win32con.STILL_ACTIVE:
                        log.warning(
                            'Failed to terminate job object for process %s: %s'
                            % (self, e))

                        # try this approach instead
                        win32process.TerminateProcess(self.__hProcess, 0)

            self.wait(timeout=timeout)
        except Exception as ex:  # pragma: no cover
            raise ProcessError("Error stopping process: %s" % ex)
예제 #2
0
    def run(self):
        pythoncom.CoInitialize()
        subprocess = self.CreateProcess()
        while not self._thread_stop and subprocess:
            try:
                rc = win32event.WaitForSingleObject(subprocess, 1000)
                logging.debug("{0} WaitForSingleObject: {1}".format(
                    self._process_name, rc))

                if rc == win32event.WAIT_FAILED:
                    logging.warning("{0} wait failed".format(
                        self._process_name))
                    continue

                if rc == win32event.WAIT_TIMEOUT:
                    continue

                if rc == win32event.WAIT_OBJECT_0:
                    exit_code = win32process.GetExitCodeProcess(subprocess)
                    logging.warning("{0} exited with code {1}".format(
                        self._process_name, exit_code))
                    if not self._thread_stop:
                        time.sleep(3)
                        subprocess = self.CreateProcess()
            except Exception as ex:
                logging.exception(ex)
                break

        if subprocess:
            logging.info("TerminateProcess {0}".format(self._process_name))
            win32process.TerminateProcess(subprocess)
def TerminateProcess(process_handle):
    if not process_handle:
        return
    if win32process.GetExitCodeProcess(
            process_handle) == win32con.STILL_ACTIVE:
        win32process.TerminateProcess(process_handle, 0)
    process_handle.close()
예제 #4
0
    def kill(self, pid, sig=None):
        """
        Kill a process with a signal
        @param pid: pid of the process to kill
        @param sig: signal. If no signal is specified signal.SIGKILL is used
        """
        pid = int(pid)
        self._log_debug("Killing process %d" % pid)
        if self.platform_is_unix:
            try:
                if sig is None:
                    sig = signal.SIGKILL

                os.kill(pid, sig)

            except OSError as e:
                raise j.exceptions.RuntimeError(
                    "Could not kill process with id %s.\n%s" % (pid, e))

        elif j.core.platformtype.myplatform.platform_is_windows:
            import win32api
            import win32process
            import win32con

            try:
                handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE,
                                              False, pid)
                win32process.TerminateProcess(handle, 0)
            except BaseException:
                raise
예제 #5
0
    def _timeout_execute(self, cmd, timeout=0):
        if timeout == 0:
            timeout = win32event.INFINITE
        cwd = os.getcwd()
        res = -1
        try:
            si = win32process.STARTUPINFO()
            render_img_path = os.path.dirname(self._renderImgTool)
            os.chdir(render_img_path)
            # si.dwFlags |= win32process.STARTF_USESHOWWINDOW

            handle = win32process.CreateProcess(None, cmd, None, None, 0,
                                                win32process.CREATE_NO_WINDOW,
                                                None, None, si)
            rc = win32event.WaitForSingleObject(handle[0], timeout)
            if rc == win32event.WAIT_FAILED:
                res = -1
            elif rc == win32event.WAIT_TIMEOUT:
                try:
                    win32process.TerminateProcess(handle[0], 0)
                except pywintypes.error as e:
                    raise DUTError('exectue {0} timeout :{1}'.format(cmd, e))
                if rc == win32event.WAIT_OBJECT_0:
                    res = win32process.GetExitCodeProcess(handle[0])
            else:
                res = 0
        finally:
            os.chdir(cwd)
        if res != 0:
            raise DUTError('fail to exec {0} res :{1}'.format(cmd, res))
        return res
예제 #6
0
def processTerminate(uPid):
    """
    Terminates the process in a nice manner (SIGTERM or equivalent).
    Returns True on success, False on failure.
    """
    fRc = False
    if sys.platform == 'win32':
        try:
            hProcess = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False,
                                            uPid)
        except:
            pass
        else:
            try:
                win32process.TerminateProcess(hProcess, 0x40010004)
                # DBG_TERMINATE_PROCESS
                fRc = True
            except:
                pass
            win32api.CloseHandle(hProcess)
    else:
        try:
            os.kill(uPid, signal.SIGTERM)
            fRc = True
        except:
            pass
    return fRc
예제 #7
0
    def stop(self, kill=False):  # pylint: disable=too-many-branches
        """Terminate the process."""
        if sys.platform == "win32":

            # Attempt to cleanly shutdown mongod.
            if not kill and self.args and self.args[0].find("mongod") != -1:
                mongo_signal_handle = None
                try:
                    mongo_signal_handle = win32event.OpenEvent(
                        win32event.EVENT_MODIFY_STATE, False,
                        "Global\\Mongo_" + str(self._process.pid))

                    if not mongo_signal_handle:
                        # The process has already died.
                        return
                    win32event.SetEvent(mongo_signal_handle)
                    # Wait 60 seconds for the program to exit.
                    status = win32event.WaitForSingleObject(
                        self._process._handle, 60 * 1000)
                    if status == win32event.WAIT_OBJECT_0:
                        return
                except win32process.error as err:
                    # ERROR_FILE_NOT_FOUND (winerror=2)
                    # ERROR_ACCESS_DENIED (winerror=5)
                    # ERROR_INVALID_HANDLE (winerror=6)
                    # One of the above errors is received if the process has
                    # already died.
                    if err.winerror not in (2, 5, 6):
                        raise
                finally:
                    win32api.CloseHandle(mongo_signal_handle)

                print("Failed to cleanly exit the program, calling TerminateProcess() on PID: " +\
                    str(self._process.pid))

            # Adapted from implementation of Popen.terminate() in subprocess.py of Python 2.7
            # because earlier versions do not catch exceptions.
            try:
                # Have the process exit with code 0 if it is terminated by us to simplify the
                # success-checking logic later on.
                win32process.TerminateProcess(self._process._handle, 0)
            except win32process.error as err:
                # ERROR_ACCESS_DENIED (winerror=5) is received when the process
                # has already died.
                if err.winerror != winerror.ERROR_ACCESS_DENIED:
                    raise
                return_code = win32process.GetExitCodeProcess(
                    self._process._handle)
                if return_code == win32con.STILL_ACTIVE:
                    raise
        else:
            try:
                if kill:
                    self._process.kill()
                else:
                    self._process.terminate()
            except OSError as err:
                # ESRCH (errno=3) is received when the process has already died.
                if err.errno != 3:
                    raise
예제 #8
0
    def TerminateProcess(self):
        retstr = ''
        rights = win32con.PROCESS_ALL_ACCESS
        handle = None
        try:
            handle = None
            handle = win32api.OpenProcess(rights, 0, self.PID)
            exit_code = win32process.TerminateProcess(handle, 0)

            retstr += '\n' + GetLineDivider()
            retstr += 'TERMINATING PROCESS\n'
            retstr += 'Process Name                  : %10s\n' % self.Name
            retstr += 'Process ID                    : %10d\n' % self.PID
            retstr += 'Success/Failure               : %10s\n' % (
                'SUCCEEDED' if exit_code != 0 else 'FAILED')
        except Exception as inst:
            if len(inst.args) == 3:
                number = inst.args[0]
                function = inst.args[1]
                message = inst.args[2]
                retstr += 'ERROR %#08x (%s): %s\n' % (number, function,
                                                      message)
            else:
                retstr += str(inst) + '\n'
        finally:
            if handle:
                win32api.CloseHandle(handle)

        return retstr + '\n' + GetLineDivider()
예제 #9
0
 def stop_app(self):
     if self.started:
         win32process.TerminateProcess(self.hp, 0)
         self.started = False
         return 'App stopped.'
     else:
         return 'App already stopped.'
예제 #10
0
파일: process.py 프로젝트: zhangxin23/mongo
    def stop(self):
        """
        Terminates the process.
        """

        if sys.platform == "win32":
            # Adapted from implementation of Popen.terminate() in subprocess.py of Python 2.7
            # because earlier versions do not catch exceptions.
            try:
                # Have the process exit with code 0 if it is terminated by us to simplify the
                # success-checking logic later on.
                win32process.TerminateProcess(self._process._handle, 0)
            except win32process.error as err:
                # ERROR_ACCESS_DENIED (winerror=5) is received when the process
                # has already died.
                if err.winerror != winerror.ERROR_ACCESS_DENIED:
                    raise
                return_code = win32process.GetExitCodeProcess(self._process._handle)
                if return_code == win32con.STILL_ACTIVE:
                    raise
        else:
            try:
                self._process.terminate()
            except OSError as err:
                # ESRCH (errno=3) is received when the process has already died.
                if err.errno != 3:
                    raise
예제 #11
0
def run_dnfbox():

    while (True):

        strExepath = r"E:\\boxgroup\\DNFBox\\DNF盒子代码\\新版DnfBox\\trunk\\product\\bin\\win32\\Debug\\DnfBoxClient.exe"

        pTuple = win32process.CreateProcess(
            strExepath.decode('utf-8').encode('gbk'), '', None, None, 0,
            win32process.CREATE_NO_WINDOW, None, None,
            win32process.STARTUPINFO())

        if (0 == len(pTuple)):
            print "Create Process Fail"

        print "Create Process Success"

        time.sleep(15)

        pList = win32process.EnumProcesses()
        if (pTuple[2] in pList):
            print "Terminate Process"
            exiCode = 0
            win32process.TerminateProcess(pTuple[0], exiCode)

        time.sleep(2)

        lstDir = os.listdir(u"E:\\boxgroup\\崩溃调试\\Dump")
        if (0 != len(lstDir)):
            for item in lstDir:
                if (-1 != item.find("dmp")):
                    return
    def StartMonitoringPower(self, browser):
        assert not self._ippet_handle, 'Called StartMonitoringPower() twice.'
        self._output_dir = tempfile.mkdtemp()
        parameters = [
            '-log_dir', self._output_dir, '-signals', 'START,QUIT', '-battery',
            'n', '-disk', 'n', '-gpu', 'n', '-enable_web', 'n', '-zip', 'n',
            '-i', '0.1'
        ]

        try:
            with contextlib.closing(
                    win32event.CreateEvent(None, True, False,
                                           START_EVENT)) as start_event:
                self._ippet_handle = self._backend.LaunchApplication(
                    IppetPath(), parameters, elevate_privilege=True)
                wait_code = win32event.WaitForSingleObject(start_event, 5000)
            if wait_code != win32event.WAIT_OBJECT_0:
                if wait_code == win32event.WAIT_TIMEOUT:
                    raise IppetError('Timed out waiting for IPPET to start.')
                else:
                    raise IppetError(
                        'Error code %d while waiting for IPPET to start.' %
                        wait_code)

        except:  # In case of emergency, don't leave IPPET processes hanging around.
            if self._ippet_handle:
                try:
                    exit_code = win32process.GetExitCodeProcess(
                        self._ippet_handle)
                    if exit_code == win32con.STILL_ACTIVE:
                        win32process.TerminateProcess(self._ippet_handle, 0)
                finally:
                    self._ippet_handle.Close()
                    self._ippet_handle = None
            raise
예제 #13
0
def exec_timeout(cmd, timeout=6):
    global lock
    exitCode = 0
    StartupInfo = win32process.STARTUPINFO()
    StartupInfo.hStdOutput = 0
    StartupInfo.hStdError = 0
    StartupInfo.hStdInput = 0
    StartupInfo.dwFlags = 0
    #lock.acquire()
    #print cmd
    #lock.release()
    try:
        hProcess, hThread, pid, dwTid = win32process.CreateProcess(
            None, cmd, None, None, 0, 0, None, None, StartupInfo)
    except:
        print 'Create Process Failed !!'
        return False
    win32file.CloseHandle(hThread)
    if win32event.WaitForSingleObject(hProcess, timeout *
                                      1000) == win32event.WAIT_OBJECT_0:
        exitCode = win32process.GetExitCodeProcess(hProcess)
        win32file.CloseHandle(hProcess)
        return exitCode
    else:
        #print 'try kill process'
        win32process.TerminateProcess(hProcess, 1)
        win32file.CloseHandle(hProcess)
        return False
예제 #14
0
 def Stop(self) -> None:
   win32api.CloseHandle(self.input)
   win32api.CloseHandle(self.output)
   win32process.TerminateProcess(self._handle, -1)
   res = win32event.WaitForSingleObject(self._handle, win32event.INFINITE)
   if res == win32event.WAIT_FAILED:
     raise Error("WaitForSingleObject failed.")
   win32api.CloseHandle(self._handle)
예제 #15
0
 def tearDown(self):
     if self.processHandle is not None:
         win32process.TerminateProcess(self.processHandle, 0)
     os.remove(os.path.join(self.basepath, 'testfile.tsk'))
     lockdir = os.path.join(self.basepath, 'testfile.tsk.lock')
     if os.path.exists(lockdir):
         shutil.rmtree(os.path.join(self.basepath, 'testfile.tsk.lock'))
     if os.path.exists(self.logfilename):
         os.remove(self.logfilename)
예제 #16
0
def close_wow(hwnd):
    process_id = get_wow_process_id(hwnd)
    print process_id
    h_process = win32api.OpenProcess(win32con.PROCESS_TERMINATE,
                                     win32con.FALSE, process_id)
    if h_process > 0:
        win32process.TerminateProcess(h_process, 0)

    win32api.TerminateProcess(h_process, 0)
예제 #17
0
파일: Win_R.py 프로젝트: yuzeming/PySQOJ
def CloseProcess(pi=None):
    if pi is not None:
        #pi  (hProcess, hThread, dwProcessId, dwThreadId)
        try:
            win32process.TerminateProcess(pi[0], 1)
        except pywintypes.error:
            pass
        win32event.WaitForSingleObject(pi[0], win32event.INFINITE)
        win32api.CloseHandle(pi[0])
예제 #18
0
def timeout_protector():
    print "Script timeout has been hit, terminating"
    if sys.platform == "win32":
        # Have the process exit with code 9 when it terminates itself to closely match the exit code
        # of the process when it sends itself a SIGKILL.
        handle = win32process.GetCurrentProcess()
        win32process.TerminateProcess(handle, 9)
    else:
        os.kill(os.getpid(), signal.SIGKILL)
예제 #19
0
 def kill(self, gracePeriod=5000):
     """
     Kill process. Try for an orderly shutdown via WM_CLOSE.  If
     still running after gracePeriod (5 sec. default), terminate.
     """
     win32gui.EnumWindows(self.__close__, 0)
     if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
         win32process.TerminateProcess(self.hProcess, 0)
         win32api.Sleep(100)  # wait for resources to be released
예제 #20
0
def kill(pid):
    hProcess = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False, pid)
    if hProcess is None:
        print "doesn't exist pid"
        return False

    ret = win32process.TerminateProcess(hProcess, 0)

    win32file.CloseHandle(hProcess)
    return ret
예제 #21
0
def xpkill(p):
    if hasattr(p, "kill"):  # only available in python 2.6+
        # UNTESTED
        p.kill()
    elif os.name == "posix":  # not available on Windows
        os.kill(p.pid, signal.SIGKILL)
    else:
        # UNTESTED
        import win32process
        return win32process.TerminateProcess(process._handle, -1)
예제 #22
0
    def Stop(self) -> int:
        """Terminates the process and waits for the process to exit.

    Returns:
      The exit code.
    """
        exit_code = win32process.GetExitCodeProcess(self._handle)
        if exit_code == win32con.STILL_ACTIVE:
            win32process.TerminateProcess(self._handle, -1)
        return self.Wait()
예제 #23
0
 def stop(self):
     if self.proc_handle is not None:
         try:
             import win32process
             print('Stopping %s' % self.name)
             win32process.TerminateProcess(self.proc_handle, 0)
             return
         except ImportError:
             pass
     print('Svnserve.stop not implemented')
예제 #24
0
 def onClose(self, event):
     if self.cfg.get('METHOD') == 'THREADING':
         if self.method_alive():
             self.subprocess.terminate()
             self.method.join()
     else:
         if win32event.WaitForSingleObject(self.method[0], 0) != 0:
             win32process.TerminateProcess(self.method[0], 0)
     self.switch = False
     self.__set_icon('SICON')
예제 #25
0
def RunEm():

    handles = []

    # First get the screen size to calculate layout.

    screenX = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    screenY = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

    # First instance will be on the left hand side of the screen.
    rect = -150, -150, 50, 50
    #handle = CreateMyProcess("C:\\Program Files\\Mozilla Firefox\\firefox.exe ", rect)
    #handles.append(handle)

    # Second instance of notepad will be on the right hand side.

    #rect = screenX/2+1, 0, screenX/2, screenY
    rect = 0, 0, screenX / 10, screenY / 4
    #handle = CreateMyProcess(r"C:\Program Files\Mozilla Firefox\firefox.exe", rect)
    handle = CreateMyProcess("notepad", rect)
    handles.append(handle)

    # Now we have the processes, wait for them both # to terminate.
    # Rather than waiting the whole time, we loop 10 times,
    # waiting for one second each time, printing a message
    # each time around the loop

    countdown = range(1, 100000)
    countdown.reverse()

    for i in countdown:

        print "Waiting %d seconds for apps to close" % i

        rc = win32event.WaitForMultipleObjects(
            handles,  # Objects to wait for.
            1,  # Wait for them all
            1000)  # timeout in milli-seconds.

        if rc == win32event.WAIT_OBJECT_0:
            # Our processes closed!
            print "Our processes closed in time."
            break

        # else just continue around the loop.
    else:
        # We didn't break out of the for loop!

        print "Giving up waiting - killing processes"
        for handle in handles:
            try:
                win32process.TerminateProcess(handle, 0)
            except win32process.error:
                # This one may have already stopped.
                pass
예제 #26
0
 def onExit(self, event):
     if self.method_alive():
         if self.cfg.get('METHOD') == 'THREADING':
             self.subprocess.terminate()
             self.method.join()
         else:
             if win32event.WaitForSingleObject(self.method[0], 0) != 0:
                 win32process.TerminateProcess(self.method[0], 0)
                 win32event.WaitForSingleObject(self.method[0], -1)
                 self.sub_thread.join()
     wx.Exit()
예제 #27
0
 def _stop_daemon(self):
     "Stop the HTTPD daemon"
     if self.proc_handle is not None:
         try:
             import win32process
             print('Stopping %s' % self.name)
             win32process.TerminateProcess(self.proc_handle, 0)
             return
         except ImportError:
             pass
     print('Httpd.stop_daemon not implemented')
예제 #28
0
    def kill(self, handle):
        ppid = win32process.GetProcessId(handle)

        #print "kill1 ",ppid
        for pid in Platform.getSubProcess(ppid):
            #print "killind pid",pid
            Platform.kill(pid)
        #print "kill2"
        ret = win32process.TerminateProcess(handle, 0)

        win32file.CloseHandle(handle)
예제 #29
0
def terminate(process):
    """ Kills a subprocess. """
    if hasattr(process, 'terminate'):
        return process.terminate()
    try:
        import win32process
        return win32process.TerminateProcess(process._handle, -1)
    except ImportError:
        import os
        import signal
        return os.kill(process.pid, signal.SIGTERM)
예제 #30
0
    def Kill(self):
        """Kill the child process.

        The child process is killed in a way that does not permit an
        orderly shutdown.  In other words, 'SIGKILL' is used under
        UNIX, not 'SIGTERM'.  On Windows, 'TerminateProcess' is used,
        and the exit code from the child process will be '1'."""

        if sys.platform == "win32":
            win32process.TerminateProcess(self._GetChildPID(), 1)
        else:
            os.kill(self._GetChildPID(), signal.SIGKILL)