Listing 3: Connecting the client side of a named pipe
// Wait for pipe connection
//
while (1)
{
printf("\nTrying to open named pipe...") ;
fflush(stdout) ;
hPipe = CreateFile(
PIPE_NAME, // pipe name
GENERIC_READ | // read/write access
GENERIC_WRITE,
0, // no sharing
NULL, // no security attr.
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
// Leave loop if pipe connected
if (hPipe != INVALID_HANDLE_VALUE) break;
// Error ERROR_FILE_NOT_FOUND means pipe does not
// exist.
//
dwLastError = GetLastError() ;
if ( ERROR_FILE_NOT_FOUND == dwLastError )
{
printf("server not ready.\n") ;
return ;
}
// CreateFile may have failed because the pipe is
// busy. In that case, we wait for pipe to become
// available by calling WaitNamedPipe. Note: Even
// when WaitNamedPipe has returned, CreateFile may
// fail again, because another client snatched the
// pipe in between.
//
if ( ERROR_PIPE_BUSY != dwLastError )
{
printf("aborted with error %d\n", dwLastError) ;
return ;
}
printf("\nAll instances busy. Waiting...") ;
fflush(stdout) ;
// Wait for pipe to become available
//
if ( ! WaitNamedPipe(PIPE_NAME, NMPWAIT_WAIT_FOREVER) )
{
printf("\nWait error.\n") ;
return ;
}
}
//End of File