阻塞管道连接命名管道不触发

Blocking pipe ConnectNamedPipe does not trigger

本文关键字:管道 连接      更新时间:2023-10-16

我想使用命名管道进行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 停止,并且不会执行任何其他指令,即使客户端连接并写入管道也是如此。 写文件(在客户端上(返回 true。

如果成功,ConnectNamedPipe会返回一个非零值,这就是它不起作用的原因。 将if (!ConnectNamedPipe(pipe, NULL))更改为if (ConnectNamedPipe(pipe, NULL))似乎工作正常。