进程间通信——命名管道

服务端

// 规定创建命名管道的程序是服务端
// 本程序服务端负责接收数据并打印
#include <stdio.h>
#include <Windows.h>

BOOL Server()
{
	char szBuffer[0x100] = { 0 };
	DWORD dwRead = 0;
	// 创建双向管道
	HANDLE hPipe = CreateNamedPipeA("\\\\.\\pipe\\hambaga", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
		1, 0, 0, 1000, NULL);
	if (INVALID_HANDLE_VALUE == hPipe)
	{
		printf("创建命名管道失败\n");
		CloseHandle(hPipe);
		return -1;
	}
	printf("创建命名管道成功,等待客户端连接...\n");
	if (ConnectNamedPipe(hPipe, NULL) == FALSE)
	{
		printf("与客户机连接失败\n");
		CloseHandle(hPipe);
		return -1;
	}

	while (1)
	{
		printf("正在等待数据: ");
		if (ReadFile(hPipe, szBuffer, 0x100, &dwRead, NULL) == FALSE)
		{
			printf("读取数据失败\n");
			break;
		}

		szBuffer[dwRead] = 0;
		printf("%s\n", szBuffer);
	}
	CloseHandle(hPipe);
	return TRUE;
}

int main()
{
	Server();
	return 0;
}

客户端

#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <stdio.h>

BOOL Client()
{
	char szBuffer[0x100] = { 0 };
	DWORD dwWrite = 0;
	if (WaitNamedPipeA("\\\\.\\pipe\\hambaga", NMPWAIT_WAIT_FOREVER) == FALSE)
	{
		printf("等待命名管道实例失败\n");
		return FALSE;
	}
	HANDLE hPipe = CreateFileA("\\\\.\\pipe\\hambaga", GENERIC_READ | GENERIC_WRITE, 0,
		NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hPipe == INVALID_HANDLE_VALUE)
	{
		printf("创建命名管道失败\n");
		CloseHandle(hPipe);
		return FALSE;
	}
	printf("连接服务器成功\n");
	while (1)
	{
		scanf("%s", szBuffer);
		if (FALSE == WriteFile(hPipe, szBuffer, strlen(szBuffer), &dwWrite, NULL))
		{
			printf("写入管道失败\n");
			break;
		}
	}
	CloseHandle(hPipe);
	return TRUE;
}

int main()
{
	Client();
	system("pause");
	return 0;
}

运行结果

在这里插入图片描述


---------------------
作者:hambaga
来源:CSDN
原文:https://blog.csdn.net/Kwansy/article/details/108088546
版权声明:本文为作者原创文章,转载请附上博文链接!
内容解析By:CSDN,CNBLOG博客文章一键转载插件

猜你喜欢

转载自blog.csdn.net/weixin_41875267/article/details/108466937