PeekNamedPipe
The PeekNamedPipe function retrieves a specified number of bytes from a named pipe. It does not consume the bytes read; the bytes are left in the pipe.
DWORD PeekNamedPipe(
_In_ HANDLE hPipe,
_In_ LPVOID lpBuf,
_In_ DWORD nBytes
);
Parameters
| Parameter | Data Type | Description |
|---|---|---|
hPipe |
HANDLE |
A handle to the named pipe. |
lpBuf |
LPVOID |
A pointer to a buffer to receive the data. This buffer must be at least nBytes bytes in size. |
nBytes |
DWORD |
The maximum number of bytes to retrieve from the pipe. |
Remarks
The PeekNamedPipe function retrieves data from a named pipe without consuming the data. The data remains in the pipe. This function is useful when you want to inspect the data in a pipe without removing it.
If the PeekNamedPipe function returns 0, the pipe may be in an error state. Call GetLastError to determine the reason for the error.
Example
#include <windows.h>
int main() {
HANDLE hPipe = CreateNamedPipe(
"\\\\MyPipe", // Pipe name
PIPE_ACCESS_DUPLEX, // Access mode
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // Pipe type and mode
1, // Max instances
1024, // Output buffer size
1024, // Input buffer size
0, // Time-out interval
NULL // Flags
);
if (hPipe == INVALID_HANDLE_VALUE) {
DWORD error = GetLastError();
printf("CreateNamedPipe failed with error %d\n", error);
return 1;
}
char buffer[10];
DWORD bytesRead;
if (PeekNamedPipe(hPipe, buffer, sizeof(buffer), &bytesRead, NULL) == 0) {
DWORD error = GetLastError();
printf("PeekNamedPipe failed with error %d\n", error);
} else {
printf("Read %d bytes: %s\n", bytesRead, buffer);
}
CloseHandle(hPipe);
return 0;
}
Troubleshooting
If PeekNamedPipe fails, check the following:
- The named pipe exists and is accessible.
- The pipe is not full.
- The pipe is not in an error state. Call
GetLastErrorto determine the reason for the error.