进程间通信 —— 命名管道(实例)

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
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值