【发布时间】:2019-02-07 17:19:31
【问题描述】:
我正在通过在 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;
}
由于编写器程序执行失败,无法测试阅读器代码,因此这里不能提及结果。
请帮忙。
【问题讨论】:
-
你搞错了。读者应该是创建管道并等待作者打开它的人。
-
Windows 何时支持
os.mkfifo?我的 Python 文档说它只是 Unix。 -
是的,我只在 UNIX 上使用它.. :)
-
您是否同时运行 reader 程序和 writer 程序?
-
改用
char const* myfifo = "/Users/username/Desktop/myProgram";。
标签: python c++ ipc named-pipes