1 year ago
#72332
sindhuja
python fork and pipe for sending and receiving messages
My application need two (python) methods to send and receive messages(arrays). I am trying to achieve this by using a pipe. I have forked two processes. I observe that if (process == 0), I can either send or receive message from one end (Please correct me if I am wrong). I want both ends of the pipe to be able to send and receive messages to each other. I am new to pipe and fork in python (and to the concept in general) and hence I am finding difficulty in identifying problem with my code. Do i have to use two pipes in order to achieve my goal?
This is the code I am trying to implement:
start, end = os.pipe()
def communication():
process1 = os.fork()
if process1:
r = os.fdopen(start, 'w')
parent_writes = [1,2,3,4]
data = json.dumps(parent_writes)
r.write(data)
print("Parent writes = ", data)
else:
childRead = os.fdopen(end)
data = childRead.read()
print("Child reads =", data)
process2 = os.fork()
if process2:
os.close(start)
w = os.fdopen(end, 'w')
child_writes = [6, 7, 8, 9]
data = json.dumps(child_writes)
w.write(data)
print("Child writes = ", data)
else:
os.close(end)
parentRead = os.fdopen(start)
arr = parentRead.read()
print("Parent reads =", arr)
communication()
This is my output and error message:
Parent writes = [1, 2, 3, 4]
Child writes = [6, 7, 8, 9]
Parent reads = [6, 7, 8, 9]
Traceback (most recent call last):
File "/Users/ssss/PycharmProjects/tttt/forkAndPipe.py", line 35, in
<module>communication()
File "/Users/ssss/PycharmProjects/tttt/forkAndPipe.py", line 17, in
communication
data = childRead.read()
OSError: [Errno 9] Bad file descriptor
Process finished with exit code 0
Unless I am mistaken, "Bad file descriptor" has got something to do with the way I am forking or closing ends of the pipe inappropriately.
Any help would be greatly appreciated.
python
python-3.x
process
pipe
fork
0 Answers
Your Answer