PeekNamedPipe always returns 0 for totalBytesAvailable

匿名 (未验证) 提交于 2019-12-03 08:51:18

问题:

  PeekNamedPipe(      tmp_pipe,                // __in       HANDLE hNamedPipe,      NULL,                  // __out_opt  LPVOID lpBuffer,      0,                     // __in       DWORD nBufferSize,      NULL,                  // __out_opt  LPDWORD lpBytesRead,      &totalBytesAvailable,  // __out_opt  LPDWORD lpTotalBytesAvail,      NULL                   // __out_opt  LPDWORD lpBytesLeftThisMessage    );  

I have written bytes to the pipe somewhere else,but totalBytesAvailable is always 0,why?

回答1:

I have found that in Windows, if you call PeekNamedPipe before calling ReadFile, it will always return zero bytes, even if there are in fact bytes to be read. You have to call ReadFile, followed by PeekNamedPipe, and keep looping until PeekNamedPipe returns zero bytes.

I have noticed that even under these circumstances, sometimes PeekNamedPipe returns zero bytes even though there are bytes left to be gotten. Must be a timing thing. The sender is going to have to preface each message with a byte count. Sigh...



回答2:

It's an old question but I haven't found the answer online so I figured I'd answer it anyway. You have to loop until the pipe reads, here's my working code:

DWORD bytesAvail = 0; while(bytesAvail==0){     if( !PeekNamedPipe(pipeHandle, NULL, 0, NULL, &bytesAvail, NULL) ){         printf("PeekNamedPipe error %d.\n", GetLastError()); //error check     } }  printf("Bytes available: %d\n", bytesAvail); 

Of course, this only works if you are sure there is data waiting to be read, otherwise you will be stuck in an endless loop because there isn't actually data to be read, so it will always be 0.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!