我在Unix系统上使用命名管道练习IPC,并尝试使用Python向FIFO文件中写入字符串,然后通过C++程序进行反转。但是Python程序挂起并且没有返回结果。
Python代码用于写入文件:
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()
程序挂起并且在此处不请求任何输入。我在程序中断时收到以下错误:
Traceback (most recent call last):
File "writer.py", line 4, in <module>
fifo=open(path,'w')
KeyboardInterrupt
从文件中读取的C++代码:
#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;
}
由于编写程序无法运行,无法测试读取器代码,因此无法在此处提及结果。
请帮忙。
char const* myfifo = "/Users/username/Desktop/myProgram";
替代。 - Eljay