进程间通信——管道代码实现

服务端

·                           创建管道CreateNamedPipe

·                           等待客户端连接ConnectNamedPipe

·                           Read 或 Write操作

·                           断开连接DisconnectNamedPipe

·                           关闭句柄


#include <windows.h>
#include <stdio.h>

const DWORD BUFSIZE = 1024;
const DWORD PIPE_TIMEOUT = 5000;

int main()
{
    HANDLE hPipe = CreateNamedPipeW(
			L"\\\\.\\pipe\\Dbzhang800Pipe",
            PIPE_ACCESS_DUPLEX,
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
            PIPE_UNLIMITED_INSTANCES,
            BUFSIZE,
            BUFSIZE,
            PIPE_TIMEOUT,
            NULL);

    if (hPipe == INVALID_HANDLE_VALUE) 
	{
        return -1;
    }

    for (;;) 
	{
        if (ConnectNamedPipe(hPipe, NULL) || (GetLastError() == ERROR_PIPE_CONNECTED)) 
		{
            DWORD dwBytesRead = 0;
            char szRequest[BUFSIZE];
            BOOL bSuccess = ReadFile (hPipe, szRequest, BUFSIZE, &dwBytesRead, NULL);
            szRequest[dwBytesRead] = '\0';
            printf("Data Received: %s\n",szRequest);
            if (! bSuccess || dwBytesRead == 0)		//读一个空字符串时退出
			{
                break;
            }
            DisconnectNamedPipe(hPipe);
        } 
		else 
		{
            CloseHandle(hPipe);
            return -2;
        }
    }

    CloseHandle(hPipe);
    return 0;
}

客户端

·                           直接使用CreateFile 连接管道

·                           对消息类型也可以使用CallNamedPipe


#include <windows.h>
#include <stdio.h>

const DWORD BUFSIZE = 1024;
const DWORD PIPE_TIMEOUT = 5000;

int main()
{
    HANDLE hFile = CreateFileW(
		L"\\\\.\\pipe\\Dbzhang800Pipe", 
		GENERIC_WRITE, 
		0, 
		NULL, 
		OPEN_EXISTING, 
		0, 
		NULL);

    if(hFile == INVALID_HANDLE_VALUE) 
	{
        printf("cannot connect to Named Pipe\n" );
    } 
	else 
	{
        DWORD dwWrite = 0;
        char szPipeUpdate[200] = "Data from Named Pipe client";
        WriteFile(hFile, szPipeUpdate, (DWORD)strlen(szPipeUpdate), &dwWrite, NULL);
        printf("%i bytes has send", (int)dwWrite);
        CloseHandle(hFile);
    }

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值