我想从管道中读取数据。读取不能阻塞主线程(所以一切都在一个单独的线程中),并且它必须是可取消的(因此我使用带有FILE_FLAG_OVERLAPPED
标志的重叠IO)
以下代码已简化,但我只删除了错误检查:
pipe = CreateNamedPipe("\\\\.\\pipe\\pipename", PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED , 0, 1, 1024, 1024, 1000, NULL);
while (1) {
// wait for either new data, or cancellation
DWORD wait = WaitForMultipleObjects(2,events,FALSE,INFINITE);
// Assume "new data event" and no error
GetOverlappedResult(pipe,&overlap,&unused,FALSE); // always succeeds
ReadFile(pipe,outputbuffer,neededsize,outputsize, &overlap); // sometimes says ERROR_IO_PENDING via GetLastError()
}
ReadFile()
设置ERROR_IO_PENDING
。ReadFile
丢失了一些新数据。准确地说,最后ReadFile()
会丢失我在上一页 ReadFile()
中所请求的数据。
我做错了什么?
编辑 - 正确的方式,再次没有错误检查:
BOOL res = ReadFile(...as before...);
if(res)
return; //success, reading was instantaneous, there was already data.
//GetLastError() is supposed to be ERROR_IO_PENDING here
wait = WaitForMultipleObjects(2,events,FALSE,INFINITE);
// Assume "new data event" and no error
res = GetOverlappedResult(pipe, &overlap, &cbRet, FALSE);
// Now the buffer you gave to ReadFile has its cbRet first bytes filled.