命名管道消息无法通过(Windows/C++)

本文关键字:Windows C++ 管道 消息 | 更新日期: 2023-09-27 18:20:11

正在尝试从命名管道中读取。据我所知,客户端正在正常连接并发送。考虑到代码是从这里的解决方案中提取的,我很难看出我把哪里搞砸了。Readfile似乎什么都没得到。它不会回来。如果关闭客户端的连接,则返回0。

有什么想法吗?

DWORD WINAPI LogManager::LogCollector(LPVOID args)
{
    LogMan *LogMgr = (LogMan*)args;
    int run; LogMgr ->GetValue(run);
    while (run != LogMan::eNONE) {
        HANDLE pipe = CreateNamedPipe("''''.''pipe''RCLogPipe", PIPE_ACCESS_INBOUND , PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL);
        ConnectNamedPipe(pipe, NULL);
        if (pipe == INVALID_HANDLE_VALUE){
            CloseHandle(pipe);
            return -1;
        }
        char line[1024];
        DWORD numRead = 0;
        if (!ReadFile(pipe, line, 1024, &numRead, NULL) || numRead < 1) return -1;
        LogMgr ->Write(line);
        LogMgr ->GetValue(run);
        CloseHandle(pipe);
    }
    return 0;
}

客户端

var client = new NamedPipeClientStream("RCLogPipe");
client.Connect();
StreamWriter writer = new StreamWriter(client);
if (client.CanWrite) writer.WriteLine("Hello'n");

命名管道消息无法通过(Windows/C++)

C#的StreamWriter可能会缓冲到刷新发生,所以您在那里回答了自己的第一个问题。C#不会用null终止字符串(ReadFile也不会——它不会假设你正在读取的数据是二进制的,因为它可能会关心你的数据可能是二进制的),但你使用的是从ReadFile中获得的数据,就像使用C字符串一样(用null终止的字符串)。因此,Write将看到{'h'e'l'l'o'w'o'r'l'd'[任意字节]}。Write将继续读取内存,直到找到一个空字符,然后停止。所以所有的垃圾都是任意的垃圾,直到Write偶然发现一个null字符。

您需要使用numRead值将其传递给Write,告诉它要查看多少缓冲区,或者使用它手动null终止字符串line[numRead] = ''0';,假设缓冲区中有空间。