def __init__(self, handle, access, pid=None): # duplicate handle for process with given pid if pid is None: pid = os.getpid() proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, pid) try: self._handle = _winapi.DuplicateHandle( _winapi.GetCurrentProcess(), handle, proc, access, False, 0) finally: _winapi.CloseHandle(proc) self._access = access self._pid = pid
def __init__(self, handle, access, pid=None): if pid is None: # We just duplicate the handle in the current process and # let the receiving process steal the handle. pid = os.getpid() proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, pid) try: self._handle = _winapi.DuplicateHandle( _winapi.GetCurrentProcess(), handle, proc, access, False, 0) finally: _winapi.CloseHandle(proc) self._access = access self._pid = pid
def detach(self): '''Get the handle. This should only be called once.''' # retrieve handle from process which currently owns it if self._pid == os.getpid(): # The handle has already been duplicated for this process. return self._handle # We must steal the handle from the process whose pid is self._pid. proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, self._pid) try: return _winapi.DuplicateHandle( proc, self._handle, _winapi.GetCurrentProcess(), self._access, False, _winapi.DUPLICATE_CLOSE_SOURCE) finally: _winapi.CloseHandle(proc)
def _set_pid(self, pid, _handle=None): if self.__pid is not None: raise RuntimeError("You can't change the pid") if not isinstance(pid, int): raise RuntimeError("a PID needs to be an integer") self.__pid = pid _children[pid] = self if _mswindows: if _handle is None: _handle = _winapi.OpenProcess(_winapi.PROCESS_ALL_ACCESS, True, pid) self.__handle = _handle elif _handle is not None: raise RuntimeError("Process handles are a Windows thing.")
def spawn_main(pipe_handle, parent_pid=None, tracker_fd=None): ''' Run code specified by data received over pipe ''' assert is_forking(sys.argv), "Not forking" if sys.platform == 'win32': import msvcrt import _winapi if parent_pid is not None: source_process = _winapi.OpenProcess( _winapi.PROCESS_DUP_HANDLE, False, parent_pid) else: source_process = None new_handle = reduction.duplicate(pipe_handle, source_process=source_process) fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY) else: from . import semaphore_tracker semaphore_tracker._semaphore_tracker._fd = tracker_fd fd = pipe_handle exitcode = _main(fd) sys.exit(exitcode)
def run(self): p = _winapi.OpenProcess(_winapi.PROCESS_ALL_ACCESS, False, self.tq_pid) os.waitpid(p, 0) os._exit(0)
def _create_handle_for_pid(self, pid): import _winapi return _winapi.OpenProcess(0x00100400, 0, pid)