简体   繁体   English

PeekNamedPipe总是为totalBytesAvailable返回0

[英]PeekNamedPipe always returns 0 for totalBytesAvailable

  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? 我已将字节写入其他地方的管道,但totalBytesAvailable始终为0 ,为什么?

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. 我发现在Windows中,如果在调用ReadFile之前调用PeekNamedPipe ,它将始终返回零字节,即使实际上有要读取的字节也是如此。 You have to call ReadFile , followed by PeekNamedPipe , and keep looping until PeekNamedPipe returns zero bytes. 您必须调用ReadFile ,然后调用PeekNamedPipe ,并继续循环,直到PeekNamedPipe返回零字节。

I have noticed that even under these circumstances, sometimes PeekNamedPipe returns zero bytes even though there are bytes left to be gotten. 我注意到即使在这些情况下,有时PeekNamedPipe返回零字节,即使还有剩余的字节。 Must be a timing thing. 必须是时间的事情。 The sender is going to have to preface each message with a byte count. 发送方必须在每个消息前面加上字节数。 Sigh... 叹...

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. 当然,这只有在您确定有数据等待读取时才有效,否则您将陷入无限循环,因为实际上没有要读取的数据,所以它总是为0。

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

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