简体   繁体   中英

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?

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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