【发布时间】:2015-05-06 22:39:56
【问题描述】:
我有一个 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++ 程序快吗?我该怎么办?
谢谢。
【问题讨论】:
-
Tangent:为什么不直接将
pipename.c_str()传递给unlink和mkfifo?您编写的代码不必要地分配内存(然后忘记释放它)。 -
if(!read(fd, buf, MAX_BUF))-- 你把read的结果扔掉了,所以你不知道你读了多少数据。代码不可能工作。