gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:04:58 25 4
gpt4 key购买 nike

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

由于writer程序执行失败,无法测试reader代码,因此这里不能提及结果。

请帮忙。

最佳答案

open() 中的 python 代码块。它正在等待读者。

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

所以,FIFO的“主人”应该是读者。这条规则可能只是风格问题。我不知道这种限制的具体原因。

这里是一些 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)

关于python - 在 C++ 和 Python 程序中使用命名管道的 IPC 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52136385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com