Use Named Pipes on Windows with CreateNamedPipe
Build a Windows named pipe server and client in C with CreateNamedPipeW, ConnectNamedPipe and message mode, handle a busy pipe and secure access to it.

Two programs on one Windows machine need to talk. They could use a socket on the loopback address, a shared file or shared memory. The tool Windows built for it is the named pipe: a two-way channel with a name in a special file system namespace, with security descriptors, message boundaries if you want them, and the same handle model as everything else. Services and their control programs use named pipes constantly, and so do browsers talking to helper processes. This post builds a server and a client in C, explains the pipe's modes and what each side must do, handles the busy case, and covers the security default that makes a pipe reachable from other machines unless you say otherwise.
The examples use the Windows 11 SDK (10.0.26100) with MSVC 19.4 on x64. The functions are documented on Microsoft Learn under "Named Pipes", with CreateNamedPipeW, ConnectNamedPipe and WaitNamedPipeW as the core.
The name
A named pipe lives in the pipe namespace, and its full name has a fixed form: two backslashes, a dot, the word pipe, a backslash and your name. For a pipe called demo on the local machine, the string in C source is written with each backslash doubled, as in the listings below. The leading dot means "this computer", and a remote machine's pipe is reached by putting the computer name there in place of the dot. The name can contain any characters except a backslash, up to 256 characters, and it is not case sensitive.
The server
A server creates the pipe, waits for a client to connect, exchanges data, and disconnects.
#include <windows.h>
#include <stdio.h>
#define PIPE_NAME L"\\\\.\\pipe\\demo"
int wmain(void)
{
HANDLE pipe = CreateNamedPipeW(
PIPE_NAME,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT |
PIPE_REJECT_REMOTE_CLIENTS,
1, /* maximum instances */
512, 512, /* output and input buffer sizes */
0, /* default client wait timeout */
NULL); /* default security */
if (pipe == INVALID_HANDLE_VALUE) {
fwprintf(stderr, L"CreateNamedPipe failed: %lu\n", GetLastError());
return 1;
}
wprintf(L"waiting for a client...\n");
fflush(stdout);
BOOL ok = ConnectNamedPipe(pipe, NULL) ||
GetLastError() == ERROR_PIPE_CONNECTED;
if (!ok) {
fwprintf(stderr, L"ConnectNamedPipe failed: %lu\n", GetLastError());
CloseHandle(pipe);
return 1;
}
char request[512];
DWORD got = 0;
if (ReadFile(pipe, request, sizeof request - 1, &got, NULL)) {
request[got] = '\0';
printf("server received: %s\n", request);
char reply[600];
int len = snprintf(reply, sizeof reply, "echo: %s", request);
DWORD sent = 0;
WriteFile(pipe, reply, (DWORD)len, &sent, NULL);
}
FlushFileBuffers(pipe);
DisconnectNamedPipe(pipe);
CloseHandle(pipe);
return 0;
}The arguments of CreateNamedPipeW carry the design.
The open mode, PIPE_ACCESS_DUPLEX, means both sides can read and write. The alternatives are PIPE_ACCESS_INBOUND, where the server only reads, and PIPE_ACCESS_OUTBOUND, where it only writes. Add FILE_FLAG_OVERLAPPED for asynchronous operations, which a server handling many clients needs.
The pipe mode is a combination. PIPE_TYPE_MESSAGE means writes keep their boundaries: one WriteFile is one message. The default, PIPE_TYPE_BYTE, is a plain stream like a socket. PIPE_READMODE_MESSAGE makes reads return whole messages, and with a buffer too small a read returns ERROR_MORE_DATA and you call again for the rest. PIPE_WAIT makes operations block. PIPE_REJECT_REMOTE_CLIENTS is explained in the security section.
The maximum instances says how many simultaneous connections the pipe name can serve. A value of 1 means one client at a time. PIPE_UNLIMITED_INSTANCES lets a server create a new instance for each client.
The buffer sizes are advisory: the system may use larger ones. The timeout is the default wait for a client that calls WaitNamedPipeW with NMPWAIT_USE_DEFAULT_WAIT.
ConnectNamedPipe blocks until a client opens the pipe. There is a subtle case that the code handles: if the client connected between CreateNamedPipeW and ConnectNamedPipe, the call fails with ERROR_PIPE_CONNECTED, which means the connection is already there and is a success. Treating it as an error is a common bug that shows up only when the client is fast.
After the exchange, FlushFileBuffers blocks until the client has read everything the server wrote. Without it, DisconnectNamedPipe can discard data that the client has not yet read. Then DisconnectNamedPipe ends the connection but keeps the pipe, so the server could call ConnectNamedPipe again for the next client, and CloseHandle destroys the instance.
The client
A client opens the pipe with the ordinary file functions, because a pipe handle works with ReadFile and WriteFile.
#include <windows.h>
#include <stdio.h>
#define PIPE_NAME L"\\\\.\\pipe\\demo"
int wmain(void)
{
HANDLE pipe = INVALID_HANDLE_VALUE;
for (;;) {
pipe = CreateFileW(PIPE_NAME, GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, 0, NULL);
if (pipe != INVALID_HANDLE_VALUE)
break;
DWORD err = GetLastError();
if (err != ERROR_PIPE_BUSY) {
fwprintf(stderr, L"cannot open pipe: %lu\n", err);
return 1;
}
if (!WaitNamedPipeW(PIPE_NAME, 5000)) {
fwprintf(stderr, L"pipe still busy after 5 s\n");
return 1;
}
}
DWORD mode = PIPE_READMODE_MESSAGE;
if (!SetNamedPipeHandleState(pipe, &mode, NULL, NULL)) {
fwprintf(stderr, L"SetNamedPipeHandleState failed: %lu\n", GetLastError());
CloseHandle(pipe);
return 1;
}
const char msg[] = "hello over the pipe";
DWORD sent = 0;
if (!WriteFile(pipe, msg, sizeof msg - 1, &sent, NULL)) {
fwprintf(stderr, L"write failed: %lu\n", GetLastError());
CloseHandle(pipe);
return 1;
}
char reply[600];
DWORD got = 0;
if (ReadFile(pipe, reply, sizeof reply - 1, &got, NULL)) {
reply[got] = '\0';
printf("client received: %s\n", reply);
}
CloseHandle(pipe);
return 0;
}Build both and run the server first, then the client in another console:
cl /nologo /W4 /DUNICODE /D_UNICODE server.c
cl /nologo /W4 /DUNICODE /D_UNICODE client.cwaiting for a client...
server received: hello over the pipeand in the second console:
client received: echo: hello over the pipeTwo details in the client are easy to miss. When the server has made all its instances busy, CreateFileW fails with ERROR_PIPE_BUSY, and the right response is WaitNamedPipeW, which waits until an instance is available and then the loop tries again. And a client always opens a pipe in byte mode by default, even when the server created it for messages, so it must call SetNamedPipeHandleState with PIPE_READMODE_MESSAGE to read whole messages. Forgetting this is the usual cause of "my message boundaries disappeared".
For a request and reply in one call, TransactNamedPipe writes and reads together, and the helper CallNamedPipeW does the whole open, transact, close sequence for a one-shot exchange.
Many clients
A server that serves several clients creates a new instance of the pipe for each, with the same name and PIPE_UNLIMITED_INSTANCES, and handles each connected client on its own thread or with overlapped I/O. The loop is:
Create an instance and call
ConnectNamedPipe.When a client connects, hand the pipe handle to a worker.
Immediately create the next instance so that the name is never without a listener.
If step 3 lags, a client calling CreateFileW between instances sees ERROR_PIPE_BUSY or ERROR_FILE_NOT_FOUND, because the name does not exist when no instance is listening. Creating the next instance before serving the current client closes that gap. For a large number of clients, use overlapped I/O with a completion port and one pipe instance per client.
Security
The security parameter decides who may connect. With NULL, the pipe gets a default descriptor derived from the creating process's token: it grants full control to the system and administrators and the creator, and read access to Everyone and to anonymous users. That default is permissive, and on a service it is often wrong. Pass a SECURITY_ATTRIBUTES with an explicit security descriptor, for example one built from an SDDL string with ConvertStringSecurityDescriptorToSecurityDescriptorW, to limit connection to specific accounts.
Remote access is the second concern. Named pipes work across the network through the SMB protocol, so a pipe is reachable from other machines unless you stop it. PIPE_REJECT_REMOTE_CLIENTS in the pipe mode refuses all remote connections, which is the right setting for a local-only service and is included in the example. Without it, a firewall and the descriptor are the only barriers.
A third issue is pipe squatting. If an attacker creates a pipe with your name before your service starts, clients connect to the attacker's server. Creating the pipe with FILE_FLAG_FIRST_PIPE_INSTANCE in the open mode makes CreateNamedPipeW fail if the name already exists, so a service learns at startup that someone is in the way. Clients that send sensitive data can check who they are talking to with GetNamedPipeServerProcessId.
The server can also learn who the client is: call ImpersonateNamedPipeClient after a read to run temporarily with the client's identity, and RevertToSelf to stop. That is how a privileged service performs an action on behalf of a user with the user's own access rights, and why a service must be careful about what it does while impersonating.
Common failures
| Code | Name | Likely cause |
|---|---|---|
| 2 | ERROR_FILE_NOT_FOUND | No server has created the pipe yet, or the name is wrong |
| 5 | ERROR_ACCESS_DENIED | The security descriptor refuses the client, or the first instance flag collided |
| 231 | ERROR_PIPE_BUSY | All instances are in use; call WaitNamedPipeW |
| 233 | ERROR_PIPE_NOT_CONNECTED | The other side has closed |
| 234 | ERROR_MORE_DATA | A message was larger than the read buffer; read again for the rest |
| 535 | ERROR_PIPE_CONNECTED | A client connected before ConnectNamedPipe; treat as success |
| 109 | ERROR_BROKEN_PIPE | The other end closed while you were reading or writing |
The names are shorter than the numbers suggest, and the message from FormatMessageW for each is clear. A first test that prints the error number, as the examples do, finds a wrong pipe name in seconds.
When a named pipe is not the right choice
For a few bytes between a parent and a child it started, an anonymous pipe from CreatePipe is simpler and needs no name. For bulk data, shared memory with an event is faster, as the file mapping post shows, because a pipe copies. For communication that might later leave the machine, sockets serve both cases with one API, and Unix domain sockets are available on Windows 10 and later with AF_UNIX, which gives a path-based local channel with the Berkeley sockets interface. Use a named pipe when you want Windows security integration, impersonation, message semantics, or compatibility with existing Windows services that already speak pipes.


