可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.