我有一个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/