Detailed description of the Python Process Communication naming pipeline, detailed description of the python process Pipeline
A pipe is a simple FIFO communication channel, which is unidirectional communication. Generally, a process is started to create an MPS queue. Then, this process creates one or more sub-processes to accept MPs queue information. Because the MPs queue is one-way communication, you often need to create two MPs queues for bidirectional communication.
A named pipe is an extension of a traditional pipe. The default pipe is an anonymous pipe, which only exists when the program is running. The named pipe is persistent and needs to be deleted when it is not needed.
The named pipe uses a file system, which is created by the mkfifo () method. Once created, two independent processes can access it, one read and the other write.
The named pipeline supports blocking read and write operations: if a process opens a file read, it will block until another process writes. However, you can specify the O_NONBLOCK option to enable the non-blocking mode.
The named pipe must be opened in read-only or write-only mode. It cannot be opened in read + write mode because it is unidirectional communication. To implement bidirectional communication, you must open two named pipelines.
The following is an example of using a named pipe in Python to implement inter-process communication.
Server
import os, timeread_path = "/tmp/pipe.in"write_path = "/tmp/pipe.out"if os.path.exists(read_path): os.remove(read_path)if os.path.exists(write_path): os.remove(write_path)os.mkfifo(write_path)os.mkfifo(read_path)rf = os.open(read_path, os.O_RDONLY)wf = os.open(write_path, os.O_SYNC | os.O_CREAT | os.O_RDWR)while True: s = os.read(rf, 1024) print "received msg: %s" % s if len(s) == 0: time.sleep(1) continue if "exit" in s: break os.write(wf, s)os.close(rf)os.close(wf)
Client
import osimport timewrite_path = "/tmp/pipe.in"read_path = "/tmp/pipe.out"wf = os.open(write_path, os.O_SYNC | os.O_CREAT | os.O_RDWR)rf = Nonefor i in range(1, 11): msg = "msg " + str(i) len_send = os.write(wf, msg) print "sent msg: %s" % msg if rf is None: rf = os.open(read_path, os.O_RDONLY) s = os.read(rf, 1024) if len(s) == 0: break print "received msg: %s" % s time.sleep(1)os.write(wf, 'exit')os.close(rf)os.close(wf)
Test
- First run server. py
- Then run client. py
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.