在C++和 Python 程序中使用命名管道的 IPC 挂起

IPC using Named Pipes in C++ and Python program hangs

本文关键字:管道 挂起 IPC C++ Python 程序      更新时间:2023-10-16

我正在通过在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;
}

因为,编写器程序无法执行,无法测试读取器代码,因此无法在此处提及结果。

请帮忙。

> python 代码块在open(). 它正在等待读者。

通常可以切换到非阻塞并使用os.open()。 使用FIFO,你会得到一个错误,ENXIO。 这基本上等同于没有读者在场。

因此,先进先出的"所有者"应该是读者。 这条规则可能只是一个风格问题。 我不知道这种限制的具体原因。

下面是一些 python 代码,演示了交错多个读取器和编写器。

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)