Dave's Brain

Browse - programming tips - win32 createnamedpipe example

Date: 2010may10
OS: Windows
Language: C/C++

Q.  How do I 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>

#define  THE_PIPE "\\\\.\\pipe\\testpipe"

main()
{
	HANDLE		hIn;
	DWORD		dwBytesRead;
	char		buf[100];

	hPipe = CreateNamedPipe(szPipe, 	// 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>

#define  THE_PIPE "\\\\.\\pipe\\testpipe"

void main()
{
	HANDLE		hOut;
	char		buf[1024];
	DWORD		len;
	DWORD		dwWritten;

	printf("pwrite: waiting for the pipe...\n");
	if (WaitNamedPipe(THE_PIPE, NMPWAIT_WAIT_FOREVER) == 0)
	{
        	printf("WaitNamedPipe failed. error=%d\n", GetLastError());
		return;
	}
	printf("pwrite: the pipe is ready\n");

	hOut = CreateFile(THE_PIPE,
		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");
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.