windows定名管道

时间:2021-12-01 03:34:36

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

  将定名管道作为一种网络编程方案时,它实际上成立了一个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; }