简体   繁体   English

FIFO管道中的数据丢失?

[英]Loss of data in a FIFO pipe?

I have a python process writing to a named pipe, and a C++ program reads it. 我有一个python进程正在写入命名管道,然后C ++程序读取它。 (I create the pipes in C++). (我用C ++创建管道)。 Well, it seems to work fine. 好吧,似乎工作正常。 However, sometimes I notice that there's loss of data. 但是,有时我会注意到数据丢失。 The data is not detected by the reader! 读取器未检测到数据! Am I doing something wrong? 难道我做错了什么?

Here's how I am creating the pipes: 这是我创建管道的方法:

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;
}

Now, I have a thread that reads the pipe like this: 现在,我有一个线程可以像这样读取管道:

     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);

In python I'm simply writing the data to the pipe by doing this: 在python中,我只是通过执行以下操作将数据写入管道:

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

What could be causing my problem? 是什么导致我的问题? The python program writes the data into the pipe successfully; python程序将数据成功写入管道; But the c++ program sometimes will not read the pipe. 但是c ++程序有时不会读取管道。 Can this be caused by the python process writing data faster than the c++ program before it could actually read it? 这可能是由于python进程在实际读取数据之前比c ++程序更快地写入数据吗? What should I do? 我该怎么办?

Thanks. 谢谢。

buf is not guaranteed to be terminated, nor is it guaranteed to not have '\\0' characters embedded in it from the code you posted. 不保证buf会终止,也不能保证您发布的代码中没有嵌入'\\0'字符。 This should work better, but may still fail if the Python code embeds a '\\0' in the data it writes: 这应该可以更好地工作,但是如果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) );

And your code doesn't properly handle an error condition should read() return -1. 而且您的代码未正确处理错误情况,应该read()返回-1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM