windows命名管道

时间:2023-03-10 05:36:28
windows命名管道

命名管道是通过网络来完成进程间的通信,它屏蔽了底层的网络协议细节。

  将命名管道作为一种网络编程方案时,它实际上建立了一个C/S通信体系,并在其中可靠的传输数据。命名管道服务器和客户机的区别在于:服务器是唯一一个有权创建命名管道的进程,也只有它能接受管道客户机的连接请求。而客户机只能同一个现成的命名管道服务器建立连接。命名管道提供了两种基本通信模式,字节模式和消息模式。在字节模式中,数据以一个连续的字节流的形式在客户机和服务器之间流动。而在消息模式中,客户机和服务器则通过一系列不连续的数据单位进行数据的收发,每次在管道上发出一条消息后,它必须作为一条完整的消息读入。

#include "stdafx.h"
#include <windows.h>
#include <stdio.h> int _tmain(int argc, _TCHAR* argv[])
{
//接受所有安全描述(也就是把管道的连接权限降到最低).
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
if( InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) )
{
// add a NULL disc. ACL to the security descriptor.
if (SetSecurityDescriptorDacl(&sd, TRUE, (PACL) NULL, FALSE))
{
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor =&sd;
sa.bInheritHandle = TRUE; //创建一个命名管道,在windows中\代表zhuan'yi两个\\代表一个\
HANDLE hNamedPipe = CreateNamedPipeA("\\\\.\\pipe\\testName",
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE, 1, 1024, 1024,0 , &sa);
//检查是否创建成功
if (hNamedPipe == INVALID_HANDLE_VALUE)
{
printf("create named pipe failed!\n");
}
else Window
{
printf("create named pipe success!\n");
}
//异步IO结构
OVERLAPPED op;
ZeroMemory(&op, sizeof(OVERLAPPED));
//创建一个事件内核对象
op.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
//等待一个客户端进行连接
BOOL b = ConnectNamedPipe(hNamedPipe, &op);
//当有客户端进行连接时,事件变成有信号的状态
if (WaitForSingleObject(op.hEvent, INFINITE) == 0)
{
printf("client connect success!\n");
}
else
{
printf("client connect failed!\n");
}
//连接成功后,进行通信,读写
char buff[100];
sprintf_s(buff, 100, "test message from server!");
DWORD cbWrite;
WriteFile(hNamedPipe, buff, strlen(buff), &cbWrite, NULL); ZeroMemory(buff, 100);
ReadFile(hNamedPipe, buff, 100, &cbWrite, NULL);
//通信完之后,断开连接
DisconnectNamedPipe(hNamedPipe);
//关闭管道
CloseHandle(hNamedPipe);
}
} system("pause");
return 0;
}

  

#include "stdafx.h"
#include <windows.h>
#include <stdio.h> int _tmain(int argc, _TCHAR* argv[])
{
//检查命名管道是否存在
BOOL b = WaitNamedPipeA("\\\\.\\pipe\\testName", NMPWAIT_WAIT_FOREVER);
//打开管道
HANDLE hFile = CreateFileA("\\\\.\\pipe\\testName",
GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
//检查是否连接成功
if (!b || hFile == INVALID_HANDLE_VALUE)
{
printf("connect failed!\n");
}
else
{
printf("connect success!\n");
}
//进行通信
char buf[100];
ZeroMemory(buf, 100);
DWORD dwRead;
ReadFile(hFile, buf, 100, &dwRead, NULL);
printf(buf);
WriteFile(hFile, "test message for client!", strlen("test message for client!"), &dwRead, NULL);
//关闭管道
CloseHandle(hFile);
system("pause");
return 0;
}