Skip to content

Instantly share code, notes, and snippets.

@sh7ning
Last active March 18, 2020 03:50
Show Gist options
  • Save sh7ning/d9cb32a5f690310740f290f7edbb2e6a to your computer and use it in GitHub Desktop.
Save sh7ning/d9cb32a5f690310740f290f7edbb2e6a to your computer and use it in GitHub Desktop.
进程通信demo
import os
import errno
import time
"""
The linux pipe buffers are implemnted as circular buffers[1].
A consequence of the circular buffer is that when it is full and a subsequent write is performed:
(a) then it starts overwriting the oldest data[2].
(b) Alternatively, the routines that manage the buffer could prevent overwriting the data and return an error or raise an exception.
Whether or not data is overwritten is up to the semantics of the buffer routines or the application using the circular buffer[2].
TODO: investigate whether namedPipes in Linux overwrite data [as in (a) above or raise error as in (b)]
TODO: use async operations; eg reading the pipe, writing to pipe etc
1. http://www.pixelbeat.org/programming/stdio_buffering/
2. https://en.wikipedia.org/wiki/Circular_buffer
"""
# os.open(read_path, os.O_RDONLY)
# os.open(write_path, os.O_SYNC | os.O_CREAT | os.O_RDWR)
# os.write(f, req)
# open(read_path, 'r').readline()[:-1]
FIFO = '/tmp/server_in.pipe'
try:
os.mkfifo(FIFO)
except OSError as e:
if e.errno != errno.EEXIST:
raise e
print("Opening FIFO...")
with open(FIFO) as fifo:
print("FIFO opened")
while True:
data = fifo.read()
if len(data) == 0:
# 这里可以休息一下继续,对后续消息没有任何影响,也不会丢包
print("Writer closed")
time.sleep(3)
print("slept for 3 seconds")
print()
print('Read: "{0}"'.format(data))
print()
# in terminal 1:
# > python named_pipe.py
# in terminal 2:
# > echo "hello world" > /tmp/server_in.pipe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment