def connect(self): """Attempts to connect to the server, but does not block. @return: True if the channel is now connected. @rtype: bool """ try: if win32pipe.WaitNamedPipe(self.__full_pipe_name, 10) != 0: self.__pipe_handle = win32file.CreateFile( self.__full_pipe_name, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, 0, None, ) return True else: return False except pywintypes.error as e: if e[0] == winerror.ERROR_FILE_NOT_FOUND: return False else: raise e
def connect_pipe(pipe_name, wait_time=10): print("py-waite for pipe connect.") retPipe = -1 errorPipe = None while True: time.sleep(0.2) try: retPipe = win32pipe.WaitNamedPipe(pipe_name, win32con.NMPWAIT_NOWAIT) if retPipe is None: break except Exception as err: errorPipe = err pass wait_time -= 1 if retPipe is not None: print("py-link error: ", errorPipe) return conn = None try: conn = win32file.CreateFile( pipe_name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None) except Exception as err: print("py-create file error: ", err) try: win32file.CloseHandle(conn) except: pass return conn
def pipe_exists(pipe_name): """Returns True if the named pipe named 'pipe_name' currently exists""" try: win32pipe.WaitNamedPipe(NamedPipeServer._get_filename(pipe_name), 1) except pywintypes.error: return False return True
def run(): r = RunTestLib() r.run_test(name='memstats', command="%s -memstats testdata/memstats.abc" % r.avm, expectedout=[ 'gross stats', 'managed overhead', 'gross stats end', 'sweep\\([0-9]+\\) reclaimed [0-9]+ whole pages' ]) if os.name != 'nt': print "pyspy requires windows named pipes, does not work with cygwin python or non-windows operating systems" else: failed = False try: import win32event import win32pipe import win32file except: failed = True print "pyspy failed to load python win32 extension FAILED" if failed == False: os.putenv('MMGC_PROFILE', '1') proc = r.run_command_async(command="%s testdata/memstats.abc" % r.avm, sleep=2) # pyspy source e = "MMgc::MemoryProfiler::DumpFatties" h = None try: h = win32event.OpenEvent(win32event.EVENT_MODIFY_STATE, False, e) except Exception: print "Error: No registered event: %s FAILED!" % e sys.exit(1) win32event.SetEvent(h) pipe = "\\\\.\\pipe\MMgc_Spy" readHandle = None while True: try: readHandle = win32file.CreateFile(pipe, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, 0, None) win32pipe.WaitNamedPipe(pipe, 100) except Exception: pass if readHandle: break while True: try: data = win32file.ReadFile(readHandle, 128) sys.stdout.write(data[1]) except: break
def _is_eg_running(): try: win32pipe.WaitNamedPipe(r'\\.\pipe\eventghost', NMPWAIT_USE_DEFAULT_WAIT) return True except win32pipe.error as err: if err[0] == ERROR_FILE_NOT_FOUND: return False raise NamedPipeConnectionError(err)
def connect(self, address): win32pipe.WaitNamedPipe(address, self._timeout) handle = win32file.CreateFile( address, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, cSECURITY_ANONYMOUS | cSECURITY_SQOS_PRESENT, 0) self.flags = win32pipe.GetNamedPipeInfo(handle)[0] self._handle = handle self._address = address
def open_pipe(name, mode="rw", timeout_ms=WAIT.INFINITE): if not name.startswith("\\\\"): name = r"\\.\pipe\%s" % name result = win32pipe.WaitNamedPipe(name, timeout_ms) read_mode = 0 if "r" in mode: read_mode |= constants.GENERIC_ACCESS.READ if "w" in mode: read_mode |= constants.GENERIC_ACCESS.WRITE hPipe = wrapped(win32file.CreateFile, name, read_mode, 0, None, fs.FILE_CREATION.OPEN_EXISTING, 0, None)
def connect(self, address): win32pipe.WaitNamedPipe(address, self._timeout) try: handle = win32file.CreateFile( address, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, cSECURITY_ANONYMOUS | cSECURITY_SQOS_PRESENT, 0) except win32pipe.error as e: # See Remarks: # https://msdn.microsoft.com/en-us/library/aa365800.aspx if e.winerror == cERROR_PIPE_BUSY: # Another program or thread has grabbed our pipe instance # before we got to it. Wait for availability and attempt to # connect again. win32pipe.WaitNamedPipe(address, RETRY_WAIT_TIMEOUT) return self.connect(address) raise e self.flags = win32pipe.GetNamedPipeInfo(handle)[0] self._handle = handle self._address = address
def Connect(self): isFirstConnect = True while True: try: self.hPipe = win32file.CreateFile(self.pipePath, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, 0, None) infoFormat = 'The named pipe {0} is connected.' info = infoFormat.format(self.pipePath) win32api.OutputDebugString(info) return self.hPipe except pywintypes.error as e: infoFormat = 'Unable to open named pipe {0}, w/err: {1}' info = infoFormat.format(self.pipePath, e.args[2]) win32api.OutputDebugString(info) if isFirstConnect: isFirstConnect = False # 如果提示没有找到文件,则等待一定时间之后再尝试打开 if e.args[0] == winerror.ERROR_FILE_NOT_FOUND: time.sleep(ReadClient.WAIT_TIMEOUT * ReadClient.MS_TO_SEC) continue elif e.args[0] == winerror.ERROR_PIPE_BUSY: # All pipes instances are busy, so wait for some seconds try: win32pipe.WaitNamedPipe(self.pipePath, ReadClient.WAIT_TIMEOUT) continue except pywintypes.error as waitError: # if waitError.args[0] == winerror.ERROR_SEM_TIMEOUT: infoFormat = '{0} {1} failed, w/err: {2}' info = infoFormat.format(waitError.args[1], self.pipePath, waitError.args[2]) win32api.OutputDebugString(info) return None else: # Exit if an error other than ERROR_FILE_NOT_FOUND or ERROR_PIPE_BUSY occurs return None else: return None
def wait_for_named_pipe_creation(pipe_path, timeout=60): import win32pipe import pywintypes while timeout > 0: try: win32pipe.WaitNamedPipe(pipe_path, 1) except pywintypes.error: yield from asyncio.sleep(0.5) timeout -= 0.5 else: return raise asyncio.TimeoutError()
def NamedPipeExistsAndReady(pipe_name): """Returns False if pipe_name does not exist. If pipe_name does exist, blocks until the pipe is ready to service clients, and then returns True. This is used as a drop-in replacement for os.path.exists() and os.access() to test for the pipe's existence. Both of those calls tickle the pipe in a way that appears to the server to be a client connecting, triggering error messages when no data is received. Although this function only needs to test pipe existence (waiting for CreateNamedPipe()), it actually winds up testing pipe readiness (waiting for ConnectNamedPipe()). This is unnecessary but harmless. """ try: win32pipe.WaitNamedPipe(pipe_name, win32pipe.NMPWAIT_WAIT_FOREVER) except pywintypes.error, e: if e[0] == winerror.ERROR_FILE_NOT_FOUND: return False raise
def open(self): if self.is_open(): raise TTransportException(TTransportException.ALREADY_OPEN) h = None conns = 0 while conns < self._max_conn_attempts: try: h = win32file.CreateFile( self._pipe_name, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_OVERLAPPED, None) except pywintypes.error as e: if e.winerror != winerror.ERROR_PIPE_BUSY: raise TTransportException( TTransportException.NOT_OPEN, 'Failed to open connection to pipe: {}'.format(e)) # Successfully connected, break out. if h is not None and h.handle != winerror.ERROR_INVALID_HANDLE: self._handle = h return # Wait for the connection to the pipe try: win32pipe.WaitNamedPipe(self._pipe_name, self._timeout) except Exception as e: if e.args[0] not in (winerror.ERROR_SEM_TIMEOUT, winerror.ERROR_PIPE_BUSY): raise TTransportException( type=TTransportException.UNKNOWN, message='Client failed to connect to server with {}'. format(e.args[0])) conns += 1 raise TTransportException( type=TTransportException.UNKNOWN, message='Client exceeded max connection attempts')
def __init__(self, name='', ptype=Type.NAMED, mode=Mode.DUPLEX, channel=Channel.MESSAGE, transport=Transport.ASYNCHRONOUS, view=View.SERVER, instances=0, buf_sz=[512, 512], timeout=None, sa=None): if name == '': self.name = 'pipe' + str(random.randint(9999, 9999999)) else: self.name = name self.ptype = ptype if not self.ptype == Pipe.Type.NAMED: raise NotImplementedError('Sorry! This pipe type is a WIP!') self.mode = mode if self.mode == Pipe.Mode.DUPLEX: self.__mode = w32p.PIPE_ACCESS_DUPLEX else: raise NotImplementedError('Sorry! This pipe modes is a WIP!') self.channel = channel if self.channel == Pipe.Channel.MESSAGE: self.__channel = w32p.PIPE_TYPE_MESSAGE # This will enable the ERROR_MORE_DATA exception although we # could handle the case of having more data in the buffer # without it. self.__channel |= w32p.PIPE_READMODE_MESSAGE else: raise NotImplementedError('Sorry! This channel mode is a WIP!') self.transport = transport if self.transport == Pipe.Transport.TRANSACTIONAL: raise NotImplementedError('Sorry! This transport mode is a WIP!') self.view = view # Using PIPE_NOWAIT in overlapped mode is deprecated and will cause # an ERROR_PIPE_LISTENING exception when using ConnectNamedPipe. # To avoid inefficient polling, which is CPU-stressing we make use of # events (aka signals!). # NOTE: If FILE_FLAG_OVERLAPPED is specified with PIPE_WAIT then # ConnectNamedPipe will not raise an ERROR_PIPE_LISTENING # exception however any read/write operation in the pipe stream # will cause that. if self.view == Pipe.View.SERVER: if self.transport == Pipe.Transport.ASYNCHRONOUS: self.__open_mode = self.__mode | w32f.FILE_FLAG_OVERLAPPED else: self.__open_mode = self.__mode self.__open_mode2 = 0 self.__pipe_mode = self.__channel | w32p.PIPE_WAIT else: self.__open_mode = w32f.OPEN_EXISTING self.__open_mode2 = w32f.FILE_FLAG_OVERLAPPED if self.__mode == w32p.PIPE_ACCESS_DUPLEX: self.__pipe_mode = w32f.GENERIC_READ | w32f.GENERIC_WRITE # Maximum pipe instances are 255 client + 1 for the server. See also: # https://msdn.microsoft.com/en-us/library/windows/desktop/aa365150%28v=vs.85%29.aspx if instances < 0: raise ValueError( 'Invalid # of instances: Only positive numbers are allowed!' ) elif instances == 0 or instances > 255: self.__instances = w32p.PIPE_UNLIMITED_INSTANCES self.instances = float('inf') else: self.__instances = instances self.instances = instances for sz in buf_sz: if sz < 0: raise ValueError( 'Buffer size cannot be negative!' ) if timeout is None: if self.view == Pipe.View.CLIENT: self.__timeout = w32p.NMPWAIT_WAIT_FOREVER else: self.__timeout = 0 # 50ms per MSDN documentation self.timeout = float('inf') elif timeout == 0: if self.view == Pipe.View.CLIENT: self.__timeout = w32p.NMPWAIT_USE_DEFAULT_WAIT else: self.__timeout = 0 # 50ms per MSDN documentation self.timeout = 50 else: self.__timeout = self.timeout = timeout if self.ptype == Pipe.Type.NAMED: if self.view == Pipe.View.SERVER: self.__hPipe = w32p.CreateNamedPipe( '\\\\.\\pipe\\' + self.name, self.__open_mode, self.__pipe_mode, self.__instances, buf_sz[1], buf_sz[0], self.__timeout, sa ) else: try: self.__hPipe = w32f.CreateFile( '\\\\.\\pipe\\' + self.name, self.__pipe_mode, 0, None, self.__open_mode, self.__open_mode2, None ) except WinT.error, e: if e.args[0] == werr.ERROR_PIPE_BUSY: try: w32p.WaitNamedPipe( '\\\\.\\pipe\\' + self.name, self.__timeout, ) except WinT.error, e: if e.args[0] == werr.ERROR_SEM_TIMEOUT: raise PipeTimeoutError( 'Connection timeout while awaiting pipe ' 'server response!', 'timeout', self.timeout ) else: self.__hPipe = w32f.CreateFile( '\\\\.\\pipe\\' + self.name, self.__pipe_mode, 0, None, self.__open_mode, self.__open_mode2, None )
def wait(self, blocking=True): win32pipe.WaitNamedPipe( self.name, blocking and win32pipe.NMPWAIT_WAIT_FOREVER or win32pipe.NMPWAIT_USE_DEFAULT_WAIT)
:param name: a valid mutex name. If `None` (the default) then an anonymous mutex is created which may be passed to threads which need to synchronise. :param take_initial_ownership: whether the mutex just created is to be owned by the creating thread. :returns: a :class:`Mutex` instance """ return Mutex(name, take_initial_ownership) def open_pipe(name, mode="rw", timeout_ms=WAIT.INFINITE): if not name.startswith(ur"\\\\"): name = ur"\\.\pipe\%s" % name result = win32pipe.WaitNamedPipe(name, timeout_ms) read_mode = 0 if "r" in mode: read_mode |= constants.GENERIC_ACCESS.READ if "w" in mode: read_mode |= constants.GENERIC_ACCESS.WRITE hPipe = wrapped(win32file.CreateFile, name, read_mode, 0, None, fs.FILE_CREATION.OPEN_EXISTING, 0, None) #~ win32pipe. def pipe(name=None): ur"""Return a pipe. If name is given a :class:`NamedPipe` is returned, otherwise an :class:`AnonymousPipe`. If name is not in the correct form for a pipe (\\\\<machine>\\pipe\\<name>) it is assumed to be a local pipe and renamed as such.