Duckware
 You are here: Duckware » Technology » PeekNamedPipe() hangs   Contact us  
PeekNamedPipe() hangs

The Windows PeekNamedPipe() is documented to return immediately. In a test environment, it works as advertised under Windows 98 and Windows Vista. But most importantly, under Windows XP Professional SP2 fully patched OS, PeekNamedPipe hangs and does not return when the pipe is empty (zero bytes).
Aug 15, 2008: At some point, Microsoft has fixed this bug, because a fully patched XP SP2 computer no longer hangs in the test code below.
Here is the test case application. We expect to see a ton of +peek and -peek output. Under Windows 98 and Vista, you do. But under Windows XP SP2, you don't.

#include "stdafx.h"
#include "windows.h"

//----------------------------------------------------------------------
DWORD WINAPI Reader( LPVOID lpParam ) {
    HANDLE hReadPipe=(HANDLE)lpParam;
    while (true) {
        char buffer[1024];
        DWORD dw;
        BOOL b = ReadFile(hReadPipe, buffer, sizeof(buffer), &dw, NULL);
        printf( "Reader res=%d dw=%d\n", b, dw );
        }
    return 0;
    }
//----------------------------------------------------------------------
DWORD WINAPI Writer( LPVOID lpParam ) {
    HANDLE hWritePipe=(HANDLE)lpParam;
    while (true) {
        DWORD dw;
        BOOL b = WriteFile(hWritePipe, "abcd", 4, &dw, NULL);
        printf( "Writer res=%d dw=%d\n", b, dw);
        Sleep(5000);        
        }
    }
//----------------------------------------------------------------------
int main(int argc, char* argv[]) {
    HANDLE hReadPipe;
    HANDLE hWritePipe;
    BOOL b = CreatePipe(&hReadPipe, &hWritePipe, NULL, 1024);
    printf( "CreatePipe res=%d\n", b );
    DWORD id;
    CreateThread(NULL,0,Reader,(LPVOID)hReadPipe,NULL,&id);
    CreateThread(NULL,0,Writer,(LPVOID)hWritePipe,NULL,&id);
    while (true) {
        DWORD avail;
        printf( "+peek\n" );
        BOOL b = PeekNamedPipe( hReadPipe, NULL, 0, NULL, &avail, NULL );
        printf( "-peek res=%d avail=%d\n", b, avail );
        }
    return 0;
    }

UPDATE: The PeekNamedPipe() problem on XP only happens when another thread has entered ReadFile() on the read end of the pipe and has not yet returned. Namely, a ReadFile() blocked on the read end of the pipe in one thread will cause any subsequent PeekNamedPipe() in a second thread to also block -- until ReadFile() in the first thread returns.

Copyright © 2000-2024 Duckware