Programming Tips - Win32: How to use CreateNamedPipe()

Date: 2010may10 Updated: 2013jan18 OS: Windows Language: C/C++ Q. Win32: How to use CreateNamedPipe() A. Here is a pair of example programs that read and write from a named pipe using byte mode. Compile into 2 separate exe's. Start pread.exe first. ----- pread.cpp -----
#include <windows.h> #include <stdio.h> LPCSTR gszThePipe = "\\\\.\\pipe\\testpipe"; main() { HANDLE hIn; DWORD dwBytesRead; char buf[100]; hPipe = CreateNamedPipe(gszThePipe, // Name PIPE_ACCESS_DUPLEX | WRITE_DAC, // OpenMode PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // PipeMode 2, // MaxInstances 1024, // OutBufferSize 1024, // InBuffersize 2000, // TimeOut NULL); // Security if (hPipe == INVALID_HANDLE_VALUE) { printf("Could not create the pipe\n"); exit(1); } printf("hPipe=%p\n", hPipe); printf("connect...\n"); ConnectNamedPipe(hIn, NULL); printf("...connected\n"); for (;;) { if (!ReadFile(hIn, buf, sizeof(buf), &dwBytesRead, NULL)) { printf("ReadFile failed -- probably EOF\n"); break; } } buf[dwBytesRead] = '\0'; printf("read [%s]\n", buf); } DisconnectNamedPipe(hIn); CloseHandle(hIn); }
----- pwrite.cpp -----
#include <windows.h> #include <stdio.h> LPCSTR gszThePipe = "\\\\.\\pipe\\testpipe"; void main() { HANDLE hOut; char buf[1024]; DWORD len; DWORD dwWritten; printf("pwrite: waiting for the pipe...\n"); if (WaitNamedPipe(gszThePipe, NMPWAIT_WAIT_FOREVER) == 0) { printf("WaitNamedPipe failed. error=%d\n", GetLastError()); return; } printf("pwrite: the pipe is ready\n"); hOut = CreateFile(gszThePipe, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hOut == INVALID_HANDLE_VALUE) { printf("CreateFile failed with error %d\n", GetLastError()); return; } printf("Opened the pipe\n"); for (int i = 0; i < 5; i++) { sprintf(buf, "This is test line %d so there.", i); len = lstrlen(buf); printf("Sending [%s]\n", buf); if (!WriteFile(hOut, buf, len, &dwWritten, NULL)) { printf("WriteFile failed\n"); break; } Sleep(1000); } CloseHandle(hOut); printf("pwrite: done\n"); }