Skip to content

Instantly share code, notes, and snippets.

@mjm522
Last active October 7, 2020 07:07
Show Gist options
  • Save mjm522/b3b687472283b1135dd2ac0178111494 to your computer and use it in GitHub Desktop.
Save mjm522/b3b687472283b1135dd2ac0178111494 to your computer and use it in GitHub Desktop.
Inter process communication using named pipes.
import time
import os, stat
import numpy as np
from multiprocessing import Process
pipename = 'myfifo'
if not stat.S_ISFIFO(os.stat(pipename).st_mode):
os.mkfifo(pipename)
def worker(pipe_name):
pipe_out = os.open(pipe_name, os.O_NONBLOCK|os.O_WRONLY)
pipe = os.fdopen(pipe_out, 'wb', buffering=0, closefd=False)
def write_message(message):
length = '{0:04d}'.format(len(message))
pipe.write(b'X')
pipe.write(length.encode('utf-8'))
pipe.write(message.encode('utf-8'))
count = 0
temp = np.zeros(6)
while True:
count += 1
temp[-1] = count
write_message(np.array2string(temp))
time.sleep(0.1)
pipe_in = os.open(pipename, os.O_NONBLOCK|os.O_RDONLY)
pipe = os.fdopen(pipe_in, 'rb', buffering=0)
proc = Process(target=worker, args=(pipename,))
proc.start()
while True:
# Wait for the message identifier
in_data = pipe.read(1)
if in_data == b'X':
#length of the message
raw_length = pipe.read(4)
message = pipe.read(int(raw_length))
# Read the message
print(np.array(message.decode('utf-8')))
elif in_data:
#If the byte read isn't an identifier, something is wrong
raise Exception('Something wrong!')
else:
time.sleep(0.1)
proc.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment