Windows命名管道是一种IPC(进程间通信)机制,在不同的进程之间进行通信。它允许一个进程向另一个进程发送数据,实现进程之间的数据共享。

使用C++ 20中的命名管道,需要包含<Windows.h>头文件,然后使用CreateNamedPipe函数创建管道,使用WriteFile和ReadFile函数进行数据的读写操作。

以下是一个简单的例子,展示了如何使用C++ 20中的命名管道进行进程间通信:

#include <Windows.h>
#include <iostream>

int main()
{
    HANDLE hPipe;
    char buffer[1024];
    DWORD dwRead;

    // 创建命名管道
    hPipe = CreateNamedPipe(
        "\\\\.\\pipe\\MyNamedPipe", // 管道名
        PIPE_ACCESS_DUPLEX, // 管道的读写方式
        PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // 管道的传输方式
        1, // 管道的最大实例数
        1024 * 16, // 缓冲区大小
        1024 * 16, // 缓冲区大小
        0, // 默认超时时间
        NULL // 安全属性
    );

    if (hPipe == INVALID_HANDLE_VALUE) {
        std::cout << "CreateNamedPipe failed with error " << GetLastError() << std::endl;
        return 1;
    }

    // 等待客户端连接
    if (!ConnectNamedPipe(hPipe, NULL)) {
        std::cout << "ConnectNamedPipe failed with error " << GetLastError() << std::endl;
        CloseHandle(hPipe);
        return 1;
    }

    // 读取客户端发送的数据
    if (!ReadFile(hPipe, buffer, sizeof(buffer), &dwRead, NULL)) {
        std::cout << "ReadFile failed with error " << GetLastError() << std::endl;
        CloseHandle(hPipe);
        return 1;
    }

    std::cout << "Received data: " << buffer << std::endl;

    // 向客户端发送数据
    char message[] = "Hello from server!";
    DWORD dwWritten;
    if (!WriteFile(hPipe, message, sizeof(message), &dwWritten, NULL)) {
        std::cout << "WriteFile failed with error " << GetLastError() << std::endl;
        CloseHandle(hPipe);
        return 1;
    }

    // 关闭管道
    CloseHandle(hPipe);

    return 0;
}

在上面的例子中,我们创建了一个名为“MyNamedPipe”的命名管道,并等待客户端连接。一旦连接建立,我们就可以使用ReadFile函数读取客户端发送的数据,并使用WriteFile函数向客户端发送数据。最后,我们使用CloseHandle函数关闭管道。

在客户端代码中,我们可以使用CreateFile函数连接到服务器创建的命名管道,并使用ReadFile和WriteFile函数进行数据的读写操作。

c++ 20 windows命名管道

原文地址: https://www.cveoy.top/t/topic/sFU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录