#include <windows.h>
#include <iostream>
int main() {
// 创建安全描述符
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
ZeroMemory(&sa, sizeof(sa));
ZeroMemory(&sd, sizeof(sd));
// 初始化安全描述符
if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) {
std::cerr << "InitializeSecurityDescriptor failed. Error: " << GetLastError() << std::endl;
return 1;
}
// 设置 DACL,允许所有用户访问
if (!SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE)) {
std::cerr << "SetSecurityDescriptorDacl failed. Error: " << GetLastError() << std::endl;
return 1;
}
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = FALSE;
// 创建命名管道
HANDLE hPipe = CreateNamedPipe(
L"\\\\.\\pipe\\MyPipe",
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
1,
512,
512,
0,
&sa
);
if (hPipe == INVALID_HANDLE_VALUE) {
std::cerr << "CreateNamedPipe failed. Error: " << GetLastError() << std::endl;
return 1;
}
std::cout << "Waiting for a client to connect..." << std::endl;
// 等待客户端连接
if (ConnectNamedPipe(hPipe, NULL) != FALSE) {
std::cout << "Client connected." << std::endl;
// 处理客户端请求
char buffer[128];
DWORD bytesRead;
ReadFile(hPipe, buffer, sizeof(buffer), &bytesRead, NULL);
buffer[bytesRead] = '\0'; // Null-terminate the string
std::cout << "Received from client: " << buffer << std::endl;
// 关闭管道
CloseHandle(hPipe);
} else {
std::cerr << "ConnectNamedPipe failed. Error: " << GetLastError() << std::endl;
}
return 0;
}