C/C++ · 2023年9月26日 0

Windows C++ 使用PIPE命名管道实现进程间通讯

本文章是介绍在Windows下,使用PIPE管道实现进程间通讯,可是实现两个进程之前相互发送读取消息。

主进程代码


#include "windows.h"
#include <iostream>
using namespace std;

#define BUF_SIZE 4096
// 定义管道名 , 如果是跨网络通信 , 则在圆点处指定服务器端程序所在的主机名
#define EXAMP_PIPE   L"\\\\.\\PIPE\\EB3F2E4B_52E2_40F9_A17D_B4A2588F23AB"   

int main(int argc, TCHAR* argv[], TCHAR* envp[])
{
    // 创建命名管道
    HANDLE hPipe = NULL;
    hPipe = CreateNamedPipe(
        EXAMP_PIPE,
        PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_MESSAGE |
        PIPE_READMODE_MESSAGE |
        PIPE_WAIT,
        PIPE_UNLIMITED_INSTANCES,
        BUF_SIZE,
        BUF_SIZE,
        0,
        NULL);

    if (hPipe == INVALID_HANDLE_VALUE)
    {
        cout << "Create Read Pipe Error" << endl;
        return FALSE;
    }


    cout << "Wait for the connection" << endl;

    // 等待客户端的连接
    if (!ConnectNamedPipe(hPipe, NULL))
    {
        cout << "Connect Failed" << endl;
        return FALSE;
    }

    DWORD dwReturn = 0;
    char szBuffer[BUF_SIZE] = { 0 };

    // 向客户端发送数据
    cout << "Wait for input" << endl;
    cin >> szBuffer;
    if (!WriteFile(hPipe, szBuffer, strlen(szBuffer), &dwReturn, NULL))
    {
        cout << "Write Failed" << endl;
    }

    // 读取客户端数据
    memset(szBuffer, 0, BUF_SIZE);
    if (ReadFile(hPipe, szBuffer, BUF_SIZE, &dwReturn, NULL))
    {
        szBuffer[dwReturn] = '\0';
        cout << szBuffer << endl;
    }
    else
    {
        cout << "Read Failed" << endl;
    }

    DisconnectNamedPipe(hPipe);
    CloseHandle(hPipe);
    return 0;
}

子进程代码


#include "windows.h"
#include <iostream>
using namespace std;

#define BUF_SIZE 4096
// 定义管道名 , 如果是跨网络通信 , 则在圆点处指定服务器端程序所在的主机名
#define EXAMP_PIPE   L"\\\\.\\PIPE\\EB3F2E4B_52E2_40F9_A17D_B4A2588F23AB"

int main(int argc, TCHAR* argv[], TCHAR* envp[])
{
    HANDLE hPipe = NULL;
    char  szBuffer[BUF_SIZE] = { 0 };
    DWORD dwReturn = 0;

    // 判断是否有可以利用的命名管道  
    if (!WaitNamedPipe(EXAMP_PIPE, NMPWAIT_USE_DEFAULT_WAIT))
    {
        cout << "No Read Pipe Accessible" << endl;
        return 0;
    }

    // 打开可用的命名管道 , 并与服务器端进程进行通信  
    hPipe = CreateFile(EXAMP_PIPE, GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL, OPEN_EXISTING, 0, NULL);

    if (hPipe == INVALID_HANDLE_VALUE)
    {
        cout << "Open Read Pipe Error" << endl;
        return 0;
    }

    cout << "Wait for the message" << endl;

    // 读取服务端发来的数据
    if (ReadFile(hPipe, szBuffer, BUF_SIZE, &dwReturn, NULL))
    {
        szBuffer[dwReturn] = '\0';
        cout << szBuffer << endl;
    }
    else
    {
        cout << "Read Failed" << endl;
    }

    // 向服务端发送数据
    memset(szBuffer, 0, BUF_SIZE);
    cin >> szBuffer;
    if (!WriteFile(hPipe, szBuffer, strlen(szBuffer), &dwReturn, NULL))
    {
        cout << "Write Failed" << endl;
    }

    CloseHandle(hPipe);
    return 0;
}