【发布时间】:2020-05-29 03:49:08
【问题描述】:
我想使用命名管道进行 IPC。 这是我试图在两个进程之间进行通信的测试客户端/服务器 客户端代码:
#include <iostream>
#include <Windows.h>
int main()
{
HANDLE pipe = CreateFileA("\\\\.\\pipe\\DokiDoki", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (pipe != INVALID_HANDLE_VALUE) {
char buffer[] = "DokiDoki from the other side :P";
DWORD bytesWritten;
WriteFile(pipe, static_cast<LPCVOID>(buffer), sizeof(buffer), &bytesWritten, NULL);
std::cout << "Done!\n";
CloseHandle(pipe);
}
else {
std::cout << "Could not get a handle to the pipe!\n";
return 1;
}
return 0;
}
服务器代码:
#include <iostream>
#include <array>
#include <Windows.h>
int main()
{
char buffer[1024];
HANDLE pipe = CreateNamedPipeA("\\\\.\\pipe\\DokiDoki", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, sizeof(buffer), sizeof(buffer), NMPWAIT_USE_DEFAULT_WAIT, NULL);
while (pipe != INVALID_HANDLE_VALUE) {
if (!ConnectNamedPipe(pipe, NULL)) {
//Setting a breakpoint here will never trigger.
DWORD bytesRead = 0;
while (ReadFile(pipe, static_cast<LPVOID>(buffer), sizeof(buffer) - 1, &bytesRead, NULL)) {
std::cout << buffer << std::endl;
}
}
DisconnectNamedPipe(pipe);
}
return 0;
}
程序在 ConnectNamedPipe 处停止并且不会执行任何其他指令,即使客户端连接并写入管道也是如此。 WriteFile(在客户端)返回 true。
【问题讨论】:
-
查看MSDN example。
-
@RemyLebeau 提醒我这个 API 有多么糟糕。
ConnectNamedPipe()应该返回一个新句柄,并且您不必重新创建管道或处理fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);废话。