简体   繁体   English

阻塞 pipe ConnectNamedPipe 不触发

[英]Blocking pipe ConnectNamedPipe does not trigger

I want to do IPC using named pipes.我想使用命名管道进行 IPC。 Here is a test client/server that I attempted to make to communicate between two processes Client code:这是我试图在两个进程之间进行通信的测试客户端/服务器客户端代码:

#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;
}

Server code:服务器代码:

#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;
}

The program stops at ConnectNamedPipe and will not execute any other instructions, even when the client connects and writes to the pipe.程序在 ConnectNamedPipe 处停止并且不会执行任何其他指令,即使客户端连接并写入 pipe 也是如此。 WriteFile (on the client) returns true. WriteFile(在客户端)返回 true。

ConnectNamedPipe returns a nonzero value if it succeeds, which is why this wasn't working.如果成功, ConnectNamedPipe将返回一个非零值,这就是它不起作用的原因。 Changing if (,ConnectNamedPipe(pipe, NULL)) to if (ConnectNamedPipe(pipe, NULL)) seems to work fine.if (,ConnectNamedPipe(pipe, NULL))更改为if (ConnectNamedPipe(pipe, NULL))似乎工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM