I'm practicing IPC by using named pipes on Unix and trying to write a string in FIFO file using python & reversing it through C++ program. But the program in Python gets hanged & returns no result.
Python Code For writing into file:
import os
path= "/home/myProgram"
os.mkfifo(path)
fifo=open(path,'w')
string=input("Enter String to be reversed:\t ")
fifo.write(string)
fifo.close()
The program hangs and doesn't ask for any input here. I get following error when I break out:
Traceback (most recent call last):
File "writer.py", line 4, in <module>
fifo=open(path,'w')
KeyboardInterrupt
C++ code for reading from file:
#include <fcntl.h>
#include <iostream>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <string.h>
#define MAX_BUF 1024
using namespace std;
char* strrev(char *str){
int i = strlen(str)-1,j=0;
char ch;
while(i>j)
{
ch = str[i];
str[i]= str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
int main()
{
int fd;
char *myfifo = "/home/myProgram";
char buf[MAX_BUF];
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
cout<<"Received:"<< buf<<endl;
cout<<"The reversed string is \n"<<strrev(buf)<<endl;
close(fd);
return 0;
}
Since, the writer program fails to execute, unable to test the reader code and hence can't mention the result here.
Please help.
The python code blocks in open(). It is waiting for a reader.
One might normally switch to nonblocking and use os.open(). With a FIFO, you will get an error, ENXIO. This basically equates to, no reader present.
So, the "owner" of the FIFO should be the reader. This rule might simply be a matter of style. I am not aware of specific reasons for this constraint.
Here is some python code that demonstrates interleaving multiple readers and writers.
import os
r1 = os.open('myfifo', os.OS_RDONLY | os.OS_NONBLOCK)
r2 = os.open('myfifo', os.OS_RDONLY | os.OS_NONBLOCK)
w1 = os.open('myfifo', os.OS_WRONLY | os.OS_NONBLOCK)
w2 = os.open('myfifo', os.OS_WRONLY | os.OS_NONBLOCK)
os.write(w1, b'hello')
msg = os.read(r1, 100)
print(msg.decode())
os.write(w2, b'hello')
msg = os.read(r2, 100)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With