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

问题描述 投票:2回答:1

我正在使用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 c++ ipc named-pipes
1个回答
1
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.