Skip to content

Instantly share code, notes, and snippets.

@komuw
Created November 1, 2018 15:23
Show Gist options
  • Select an option

  • Save komuw/52f796677b88773f9b3d573526f44809 to your computer and use it in GitHub Desktop.

Select an option

Save komuw/52f796677b88773f9b3d573526f44809 to your computer and use it in GitHub Desktop.
python named pipe
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
"""
FIFO = 'komusNamedPipe'
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()
print("end of read program")
# in terminal 1:
# > python read_named_pipe.py
# in terminal 2:
# > echo "sina tabu" > komusNamedPipe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment