CreateNamedPipe – Creating Named Pipe Server

Named Pipes are useful in Inter Process communication. Pipes will always have two ends. One on the Server (usually to listen and reply) and the client which connects and sends messages. So Pipes can be used in communicating among two programs very conveniently.

Named Pipe server can be created using CreateNamedPipe function. This function creates the pipe and returns a handle for the Pipe created. Then ConnectNamedPipe should be used to listen for any incoming connections from the client. Typically this waits in a infinite loops to keep receiving messages.

The following sample uses both CreateNamedPipe and ConnectNamedPipe to receive and print the messages. See the corresponding Named Pipe client.

CreateNamedPipe – Sample:

#include <windows.h>
#include <stdio.h>
#define BUFSIZE 1024
#define PIPE_TIMEOUT 5000

int main()
BOOL fConnected;
LPTSTR lpszPipename = "\\\\.\\pipe\\SamplePipe";
CHAR chRequest[BUFSIZE];           DWORD cbBytesRead;
BOOL fSuccess;
hPipe = CreateNamedPipe ( lpszPipename, PIPE_ACCESS_DUPLEX, // read/write access                                                   PIPE_TYPE_MESSAGE | // message type pipe                                                   PIPE_READMODE_MESSAGE | // message-read mode                                                   PIPE_WAIT, // blocking mode                                                   PIPE_UNLIMITED_INSTANCES, // max. instances                                                   BUFSIZE, // output buffer size                                                   BUFSIZE, // input buffer size                                                   PIPE_TIMEOUT, // client time-out                                                   NULL); // no security attribute
return true;
for (;;)
// Trying connectnamedpipe in sample for CreateNamedPipe
// Wait for the client to connect; if it succeeds,
// the function returns a nonzero value. If the function returns
// zero, GetLastError returns ERROR_PIPE_CONNECTED.
fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if (fConnected)
fSuccess = ReadFile (hPipe, // handle to pipe
chRequest, // buffer to receive data
BUFSIZE, // size of buffer
&cbBytesRead, // number of bytes read
// not overlapped I/O
chRequest[cbBytesRead] = '\0';
printf("Data Received: %s\n",chRequest);
if (! fSuccess || cbBytesRead == 0)
// The client could not connect in the CreateNamedPipe sample, so close the pipe.
return 1;

//End of sample using CreateNamedPipe

The above program waits infinitely for Client Pipes to connect from \\.\pipe\SamplePipe. When a client is connected and data is received, it is printed on to the console.