[英]IPC using Named Pipes in C++ and Python program hangs
我正在通過在 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;
}
由於編寫器程序無法執行,無法測試讀取器代碼,因此無法在此處提及結果。
請幫忙。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.