def server_pipe_read(pipe_name, string_read_fxn): """Create a pipe server that reads only. When a message is read, execute string_read_fxn on the received string. Args: pipe_name (str): name of named pipe string_read_fxn (fxn_handle): handle to function that accepts str """ filearg_pipe = server_create_named_pipe(pipe_name) while True: client_done = False LOGGER.info("Waiting for client...") server_connect_and_wait(filearg_pipe) LOGGER.info("Got client.") while not client_done: # keep reading from this client until it closes access to pipe try: resp_str = pipe_read(filearg_pipe) except pywintypes.error as err: (winerror, funcname, strerror) = err.args if winerror == 109: LOGGER.info("Client closed access to pipe.") client_done = True else: LOGGER.error("Windows error:\n %s\n %s\n %s", winerror, funcname, strerror) client_done = True raise else: string_read_fxn(resp_str) finally: if client_done: # Disconnect client from pipe win32pipe.DisconnectNamedPipe(filearg_pipe)
def close(self): """Close file. """ if self._handle: try: flags = win32pipe.GetNamedPipeInfo(self._handle)[0] except: flags = 0 if flags & win32con.PIPE_SERVER_END: win32pipe.DisconnectNamedPipe(self._handle) # TODO: if pipe, need to call FlushFileBuffers? def _close_(self, rc, n): win32file.CloseHandle(self._handle) self._overlap = None _AsyncFile._notifier.unregister(self._handle) self._handle = None self._read_result = self._write_result = None self._read_coro = self._write_coro = None self._buflist = [] if self._overlap.object: self._overlap.object = partial_func(_close_, self) win32file.CancelIo(self._handle) else: _close_(self, 0, 0)
def get_mouse_data(): import win32file import win32pipe PIPE_NAME = r'\\.\pipe\test_pipe' PIPE_BUFFER_SIZE = 1 while True: named_pipe = win32pipe.CreateNamedPipe( PIPE_NAME, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT | win32pipe.PIPE_READMODE_MESSAGE, win32pipe.PIPE_UNLIMITED_INSTANCES, PIPE_BUFFER_SIZE, PIPE_BUFFER_SIZE, 500, None) while True: try: win32pipe.ConnectNamedPipe(named_pipe, None) data = win32file.ReadFile(named_pipe, PIPE_BUFFER_SIZE, None) # if data is None or len(data) < 2: # continue print('receive msg:', int.from_bytes(data[1], 'big')) except BaseException as e: print("exception:", e) break win32pipe.DisconnectNamedPipe(named_pipe)
def close(self): try: win32pipe.DisconnectNamedPipe(self.pipe) win32file.CloseHandle(self.pipe) return 1 except: return 0
def read(self): if (self.bIsWindows): import pywintypes, win32file data = 0 try: (hr, data) = win32file.ReadFile(self.fileobject, 1) except pywintypes.error as e: import winerror if (e.winerror == winerror.ERROR_BROKEN_PIPE): import win32pipe, win32api win32pipe.DisconnectNamedPipe(self.fileobject) win32api.CloseHandle(self.fileobject) if (self.mode == "r"): direction = win32pipe.PIPE_ACCESS_INBOUND elif (self.mode == "w"): direction = win32pipe.PIPE_ACCESS_OUTBOUND self.fileobject = win32pipe.CreateNamedPipe( self.path, direction, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT, 1, 65536, 65536, 300, None) raise FIFOClosedException() else: raise return data elif (self.bIsPosix): import os # print("Reading data") data = os.read(self.fileobject, 1) if (len(data) == 0): raise FIFOClosedException() return data
def server(name, callback_func): buffer = 4096 timeout = 1000 error = False while True: if error: time.sleep(1) error = False handle = win32pipe.CreateNamedPipe( name, win32pipe.PIPE_ACCESS_INBOUND, win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT, win32pipe.PIPE_UNLIMITED_INSTANCES, buffer, buffer, timeout, None) if handle == win32file.INVALID_HANDLE_VALUE: error = True continue try: if win32pipe.ConnectNamedPipe(handle) != 0: error = True else: code, message = win32file.ReadFile(handle, buffer, None) if code == 0: callback_func(message) else: error = True except Exception: error = True finally: win32pipe.DisconnectNamedPipe(handle) win32file.CloseHandle(handle)
def start_listen(pipe_name): pipe = win32pipe.CreateNamedPipe( pipe_name, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT, 1, 65536, 65536, 0, None) # Waiting for client win32pipe.ConnectNamedPipe(pipe, None) win32pipe.SetNamedPipeHandleState( pipe, win32pipe.PIPE_READMODE_MESSAGE, None, None) while True: # Got client try: # Trying to read the message received in the pipe get_command = win32file.ReadFile(pipe, 6) decoded_message = str(get_command[1].decode()) # If the message is *STOP*, we break from the loop if decoded_message == "*STOP*": break except pywintypes.error as e: pass if pipe is not None: win32pipe.DisconnectNamedPipe(pipe) win32pipe.ConnectNamedPipe(pipe, None) win32file.CloseHandle(pipe) return
def close(self): """Similar to 'close' of file descriptor. """ if self._handle: try: flags = win32pipe.GetNamedPipeInfo(self._handle)[0] except Exception: flags = 0 if flags & win32con.PIPE_SERVER_END: win32pipe.DisconnectNamedPipe(self._handle) # TODO: if pipe, need to call FlushFileBuffers? def _close_(rc, n): win32file.CloseHandle(self._handle) self._overlap = None if self._notifier: self._notifier.unregister(self._handle) self._handle = None self._read_result = self._write_result = None self._read_task = self._write_task = None self._buflist = [] if self._overlap.object: self._overlap.object = _close_ win32file.CancelIo(self._handle) else: _close_(0, 0)
def heart(self, lock): try: while self.flag: print("心跳") try: conn = win32pipe.ConnectNamedPipe(self.named_pipe, None) if conn: _str = tobuff(8, 202, b'{}') print(f'写入ipc管道的信息为== {_str}') with lock: win32file.WriteFile(self.named_pipe, _str) print("写入心跳结束") time.sleep(5) else: time.sleep(0.1) print("心跳命名管道还未连接") continue except BaseException as e: print("read1 exception:", e) break print("命名管道要关闭通道啦") finally: try: print('关闭通道') win32pipe.DisconnectNamedPipe(self.named_pipe) except: pass
def _disconnectfifo(self, process_info): if _is_win: unique_id = process_info["unique_id"] handle = self._control_handles[unique_id] win32pipe.DisconnectNamedPipe(handle) win32file.CloseHandle(handle) del self._control_handles[unique_id]
def close(self): """ Generic close method, as both server and client rely on closing pipes in the same way """ if self._handle is not None: win32pipe.DisconnectNamedPipe(self._handle) self._handle = None
def close(self): if self.view == Pipe.View.SERVER: if self.transport == Pipe.Transport.SYNCHRONOUS: w32f.FlushFileBuffers(self.__hPipe) w32p.DisconnectNamedPipe(self.__hPipe) else: self.__hPipe.Close() w32api.CloseHandle(self.__hPipe)
def close(self): try: win32file.CloseHandle(self.pipe_handle) win32pipe.DisconnectNamedPipe(self.pipe_handle) except: #print sys.exc_info() pass self.pipe_open = False
def close(self): if self.socket is not None: self.socket.close() if self.pipe is not None: if self._server: win32pipe.DisconnectNamedPipe(self.pipe) winutils.close_handle(self.pipe, vlog.warn) winutils.close_handle(self._read.hEvent, vlog.warn) winutils.close_handle(self._write.hEvent, vlog.warn)
def ClosePipe(self): if not self.p is None: if (self.os == 'nt'): win32pipe.DisconnectNamedPipe(self.p) elif (self.os == 'posix'): os.close(self.p) if (self.os == 'posix' and self.f == 0): os.unlink(self.sPipeName)
def close(self): """Closes the channel to the client. """ try: win32file.WriteFile(self.__pipe_handle, struct.pack("I", 0)) win32file.FlushFileBuffers(self.__pipe_handle) finally: win32pipe.DisconnectNamedPipe(self.__pipe_handle) self.__pipe_handle = None
def run(self): try: # create pipe if isWindows(): self.pipe = win32pipe.CreateNamedPipe( self.PIPE_NAME_WIRESHARK, win32pipe.PIPE_ACCESS_OUTBOUND, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT, 1, 65536, 65536, 300, None, ) elif isLinux(): self.pipe = open(self.PIPE_NAME_WIRESHARK, 'wb') while True: try: # connect to pipe (blocks until Wireshark appears) if isWindows(): win32pipe.ConnectNamedPipe(self.pipe, None) elif isLinux(): open(self.PIPE_NAME_WIRESHARK, 'wb') # send PCAP global header to Wireshark ghdr = self._createPcapGlobalHeader() if isWindows(): win32file.WriteFile(self.pipe, ghdr) elif isLinux(): self.pipe.write(ghdr) self.pipe.flush() except: continue else: print 'INFO: Wireshark connected' with self.dataLock: self.wiresharkConnected = True # wait until need to reconnect self.reconnectToPipeEvent.wait() self.reconnectToPipeEvent.clear() finally: print 'INFO: Wireshark disconnected' with self.dataLock: self.wiresharkConnected = False # disconnect from pipe if isWindows(): win32pipe.DisconnectNamedPipe(self.pipe) elif isLinux(): self.pipe.close() except Exception as err: logCrash(self.name, err)
def close(self): """Closes the channel to the client.""" try: # 2->TODO struct.pack|unpack in python < 2.7.7 does not allow unicode format string. win32file.WriteFile(self.__pipe_handle, compat.struct_pack_unicode("I", 0)) win32file.FlushFileBuffers(self.__pipe_handle) finally: win32pipe.DisconnectNamedPipe(self.__pipe_handle) self.__pipe_handle = None
def write(self, text, close=False): "close - close pipe to emulate EOF" win32pipe.ConnectNamedPipe(self.pipe, None) text += self.lineterm win32file.WriteFile(self.pipe, text.encode(self.encoding)) if close: # http://comp.os.linux.questions.narkive.com/2AW9g5yn/sending-an-eof-to-a-named-pipe self.close() else: win32pipe.DisconnectNamedPipe(self.pipe)
def run(self): # REJECT doesn't do anything under XP, but XP is gone anyway PIPE_REJECT_REMOTE_CLIENTS = 0x00000008 FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000 buffer_ = 4096 timeout_ms = 50 try: handle = win32pipe.CreateNamedPipe( self._filename, win32pipe.PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE, (win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS), win32pipe.PIPE_UNLIMITED_INSTANCES, buffer_, buffer_, timeout_ms, None) except pywintypes.error: # due to FILE_FLAG_FIRST_PIPE_INSTANCE and not the first instance self._stopped = True self._event.set() return if handle == win32file.INVALID_HANDLE_VALUE: self._stopped = True self._event.set() return self._event.set() while 1: data = bytearray() try: win32pipe.ConnectNamedPipe(handle) while 1: try: code, message = win32file.ReadFile( handle, buffer_, None) except pywintypes.error: break data += message win32pipe.DisconnectNamedPipe(handle) except pywintypes.error: # better not loop forever.. break finally: if self._stopped: break if data: self._process(bytes(data)) try: win32file.CloseHandle(handle) except pywintypes.error: pass
def SvcDoRun(self): # We create our named pipe. pipeName = "\\\\.\\pipe\\PyPipeService" openMode = win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED pipeMode = win32pipe.PIPE_TYPE_MESSAGE # When running as a service, we must use special security for the pipe sa = pywintypes.SECURITY_ATTRIBUTES() # Say we do have a DACL, and it is empty # (ie, allow full access!) sa.SetSecurityDescriptorDacl(1, None, 0) pipeHandle = win32pipe.CreateNamedPipe( pipeName, openMode, pipeMode, win32pipe.PIPE_UNLIMITED_INSTANCES, 0, 0, 6000, # default buffers, and 6 second timeout. sa) # Loop accepting and processing connections while 1: try: hr = win32pipe.ConnectNamedPipe(pipeHandle, self.overlapped) except error, details: print "Error connecting pipe!", details pipeHandle.Close() break if hr == winerror.ERROR_PIPE_CONNECTED: # Client is fast, and already connected - signal event win32event.SetEvent(self.overlapped.hEvent) # Wait for either a connection, or a service stop request. timeout = win32event.INFINITE waitHandles = self.hWaitStop, self.overlapped.hEvent rc = win32event.WaitForMultipleObjects(waitHandles, 0, timeout) if rc == win32event.WAIT_OBJECT_0: # Stop event break else: # Pipe event - read the data, and write it back. # (We only handle a max of 255 characters for this sample) try: hr, data = win32file.ReadFile(pipeHandle, 256) win32file.WriteFile(pipeHandle, "You sent me:" + data) # And disconnect from the client. win32pipe.DisconnectNamedPipe(pipeHandle) except win32file.error: # Client disconnected without sending data # or before reading the response. # Thats OK - just get the next connection continue
def handleError(self, result): reset_pipe = False if result == winerror.ERROR_BROKEN_PIPE: win32pipe.DisconnectNamedPipe(self.pipe_handle) reset_pipe = True elif result == winerror.ERROR_NO_DATA: reset_pipe = True if reset_pipe: self.pipe_handle = None self.pipe_open = False
def close(self): """ Close Pipe and associated handle. """ if self._pipe is not None: try: win32pipe.DisconnectNamedPipe(self._pipe) except pywintypes.error: # clients may trow error if pipe is already disconnected pass win32api.CloseHandle(self._pipe) self._pipe = None
def close(self): if self.socket is not None: self.socket.close() if self.pipe is not None: if self._server: # Flush the pipe to allow the client to read the pipe # before disconnecting. win32pipe.FlushFileBuffers(self.pipe) win32pipe.DisconnectNamedPipe(self.pipe) winutils.close_handle(self.pipe, vlog.warn) winutils.close_handle(self._read.hEvent, vlog.warn) winutils.close_handle(self._write.hEvent, vlog.warn)
def run(self, security_attributes): """ Handles the creation of the pipe. Windows SACL and DACL data for creating the pipe. :type security_attributes: win32security.SECURITY_ATTRIBUTES instance :return: None :rtype: None """ import eg eg.PrintDebugNotice('Named Pipe: Creating pipe {0}'.format( self._pipe_id)) pipe = win32pipe.CreateNamedPipe( r'\\.\pipe\eventghost', PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_WAIT | PIPE_READMODE_MESSAGE, PIPE_UNLIMITED_INSTANCES, 4096, 4096, 5, security_attributes) win32pipe.ConnectNamedPipe(pipe, None) data = win32file.ReadFile(pipe, 4096) self.is_waiting = False if not self._parent.running_pipes[-1].is_waiting == self: self._parent.running_pipes += [ Pipe(self._parent, self._parent.get_pipe_id(), security_attributes) ] eg.PrintDebugNotice('Pipe {0}: Data received'.format(self._pipe_id)) if data[0] == 0: event = threading.Event() res = [''] self._parent.process_command.add(self._pipe_id, data[1], res, event) while not event.isSet(): pass win32file.WriteFile(pipe, str(repr(res[0]))) win32pipe.DisconnectNamedPipe(pipe) win32file.CloseHandle(pipe) else: try: raise NamedPipeDataError('Pipe {0}: Unknown Error: {1}'.format( self._pipe_id, str(data))) except NamedPipeDataError: traceback.print_exc() self._parent.running_pipes.remove(self)
def heart(self): try: while self.q.empty(): self.write_to_ipc('') time.sleep(4) logging.info("心跳停止循环") finally: try: print('关闭通道') win32pipe.DisconnectNamedPipe(self.named_pipe) except: pass
def Close(self): ''' Close out this pipe cleanly, waiting for reader to empty its data. ''' # Close the pipe. print('Closing ' + self.pipe_path) # The routine for closing is described here: # https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipe-operations win32file.FlushFileBuffers(self.pipe_file) win32pipe.DisconnectNamedPipe(self.pipe_file) win32file.CloseHandle(self.pipe_file) return
def SendData(self, data): try: if not self.hasClient: win32pipe.ConnectNamedPipe(self.pipe, None) self.hasClient = True win32file.WriteFile(self.pipe, data) win32file.FlushFileBuffers(self.pipe) except Exception: if self.hasClient: win32pipe.DisconnectNamedPipe(self.pipe) self.hasClient = False return
def read(self): win32pipe.ConnectNamedPipe(self.pipe, None) data = b'' while True: try: data += win32file.ReadFile(self.pipe, 4096)[1] except pywintypes.error as e: if e.winerror == 109: # Error Broken Pipe break else: raise e win32pipe.DisconnectNamedPipe(self.pipe) return data
def pipe_connect(self): if self.pipe_status == "connected": try: win32pipe.DisconnectNamedPipe(self.pipe) except: pass self.pipe_status = "disconnected" if self.pipe_status == "disconnected": self.pipe_status = "waiting" self.pipe_connect_thread = threading.Thread(target=do_pipe_connect, args=(self.pipe, self.connectq)) self.pipe_connect_thread.daemon = True self.pipe_connect_thread.start()