【问题标题】:IPC using Named Pipes in C++ and Python program hangs在 C++ 和 Python 程序中使用命名管道的 IPC 挂起
【发布时间】: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


【解决方案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)

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    相关资源
    最近更新 更多