python - FIFO 管道中的数据丢失?

标签 python c++ ipc fifo

我有一个 python 进程写入一个命名管道,一个 C++ 程序读取它。 (我用 C++ 创建管道)。好吧,它似乎工作正常。但是,有时我会注意到数据丢失。读取器未检测到数据!我做错了什么吗?

这是我创建管道的方式:

void create_pipes(string pipename){

    char * cstr1 = new char [pipename.length()+1];
    strcpy (cstr1, pipename.c_str());

    cout << "Creating " << pipename << " pipe..." << endl;
    unlink (cstr1); // Delete pipe
    int result = mkfifo (cstr1, S_IRUSR| S_IWUSR);  // Create Pipe
    if( result == -1 ){
         cout << "There was en error creating the pipe! " << result << endl;
         //return 0;
    }
    else
        cout << "Pipe created!" << endl;
}

现在,我有一个像这样读取管道的线程:

     int fd = open(cstr1, O_RDONLY);  // Open the pipe


    while( running_threads ){

        if(!read(fd, buf, MAX_BUF))
            continue;
        string line(buf);
        if( buf != "" ){
            //cout << line;
            pipe_r.DECODE_PIPE_DATA(line);
        }
    }

    cout << "Thread terminated" << endl;

    close(fd);

在 python 中,我只是通过这样做将数据写入管道:

def write_pipe(file_string):
    while True:
        try:
            pipe.write(file_string)
            pipe.flush()
            break
        except:
            print "Error while writing to pipe"
            continue

是什么导致了我的问题? python程序成功将数据写入管道;但是c++程序有时不会读取管道。这可能是由于 python 进程在实际读取数据之前写入数据的速度比 c++ 程序快造成的吗?我该怎么办?

谢谢。

最佳答案

buf 不保证会被终止,也不保证不会从您发布的代码中嵌入 '\0' 字符。这应该可以更好地工作,但如果 Python 代码在它写入的数据中嵌入了 '\0' 可能仍然会失败:

while( running_threads )
{
    ssize_t bytesRead = read(fd, buf, MAX_BUF);
    if ( bytesRead < 0 )
         break;
    else if ( bytesRead == 0 )
         continue;

    string line( buf, static_cast<size_t>(bytesRead) );

如果 read() 返回 -1,您的代码没有正确处理错误情况。

关于python - FIFO 管道中的数据丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30088928/

相关文章:

python - Unicode 在 tkinter 中显示不正确

c++ - qticon 只显示在我的电脑上

linux - fork 和IPC机制

python - 大容量插入错误代码 3 : The system cannot find the path specified

python - Eclipse osx 中的 MySQLdb

c++ - 使用非成员函数是一种好习惯吗?

c++ - 使用包含键和结构的映射执行 set_intersection 时出错

c - 尝试使用 POSIX 消息队列创建消息队列时权限被拒绝

c++ - 序列化作为一种​​IPC机制?

python - 在 Python 中查找包含来自另一个列表的子字符串的列表元素