1、最简单的例子:
服务端:
#include <windows.h>
#include <stdio.h>
void main(void)
{
HANDLE PipeHandle;
DWORD BytesRead;
CHAR buffer[256] = {0};
if ((PipeHandle = CreateNamedPipe("\\\\.\\Pipe\\mypipe",PIPE_ACCESS_DUPLEX,PIPE_TYPE_BYTE|PIPE_READMODE_BYTE,1,0,0,1000,NULL)) == INVALID_HANDLE_VALUE)
{
printf("CreateNamedPipe failed with error %x \n",GetLastError());
return;
}
printf("Server is now running \n");
if (ConnectNamedPipe(PipeHandle,NULL) == 0)
{
printf("ConnectNamePipe failed with error %x \n",GetLastError());
CloseHandle(PipeHandle);
return;
}
if(ReadFile(PipeHandle,buffer,sizeof(buffer),&BytesRead,NULL) <= 0)
{
printf("ReadFile failed with error %x \n",GetLastError());
CloseHandle(PipeHandle);
return;
}
printf("byteread = %d,buffer = %s \n",BytesRead,buffer);
if (DisconnectNamedPipe(PipeHandle) == 0)
{
printf("DisconnectNamedPipe failed with error %x \n",GetLastError());
return;
}
CloseHandle(PipeHandle);
system("pause");
}
注意:同步情况下,ReadFile是阻塞读,遇到下列一个情况返回:
(1)A write operation completes on the write end of the pipe.
(2)The number of bytes requested is read.
(3)An error occurs.
客户端:
#include <windows.h>
#include <stdio.h>
void main(void)
{
HANDLE PipeHandle;
DWORD BytesWritten;
if (WaitNamedPipe("\\\\.\\Pipe\\mypipe", NMPWAIT_WAIT_FOREVER) == 0)
{
printf("CreateNamedPipe failed with error %x \n",GetLastError());
return;
}
if ((PipeHandle = CreateFile("\\\\.\\Pipe\\mypipe",GENERIC_READ | GENERIC_WRITE, 0 ,(LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL)) == INVALID_HANDLE_VA