windows-pipe-进程间通信1

来源:互联网 发布:java程序员工作业绩 编辑:程序博客网 时间:2024/06/05 20:09

稍微研究了一下windows各种进程通信,要求复杂度小、高效率的、双向的、不跨计算机的(不涉及网络的),只专注本地进程通信,总结出2种方式:
第一种:windows named pipe
windows pipe可以实现双向通信,一个pipe就能实现,如果涉及阻塞、同步异步、锁…这带来了复杂度提升,因此觉得一个pipe只要专注单向传输就好了,如果要涉及双向传输,使用2个pipe。以下是一种单向传输的实现,适用于高速同步模型:

server.cpp,用来接收消息:

#include<Windows.h>#include<iostream>#include<chrono>#include<future>using std::cout;using std::endl;int main(void){    HANDLE hPipe;    char buffer[1024];    DWORD readCount;    hPipe = CreateNamedPipe(        TEXT("\\\\.\\pipe\\mypip"),//管道名称,有格式限定[\\.\pipe\pipe_name]        PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,//创建模式:可读可写 |不允许多个实例        PIPE_WAIT | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,//管道属性,对管道的连接、读、写都是阻塞的|是字节管道|以字节读取        1,      //只能有一个管道实例        1024 ,  //发送缓冲区大小        1024 ,  //接收缓冲区大小        0,      //超时,虽然是0,仍然默认会有50ms的超时时间(参考msdn)        NULL);    while (hPipe != INVALID_HANDLE_VALUE)    {        cout << "start connecting..." << endl;        if (ConnectNamedPipe(hPipe, NULL) != FALSE)         {            cout << "connect-pipe-pass" << endl;            while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &readCount, NULL) != FALSE)            {                cout << "read-pass" << endl;                buffer[readCount] = '\0';                cout << "received:" << buffer << endl;                //std::this_thread::sleep_for(std::chrono::milliseconds(500));//模仿接收阻塞的情况            }        }        DisconnectNamedPipe(hPipe);    }    return 0;}

client.cpp,用来发送消息:

#include<Windows.h>#include<string>#include<iostream>int main(void){    HANDLE hPipe;    DWORD bytesWritten;    for (size_t i = 0; i < 50; i++)    {        WaitNamedPipe(TEXT("\\\\.\\pipe\\mypip"), NMPWAIT_WAIT_FOREVER);//1,等待pip就绪        hPipe = CreateFile(            TEXT("\\\\.\\pipe\\mypip"),         //2,连接pip            GENERIC_WRITE,            0,            NULL,            OPEN_EXISTING,            0,            NULL);        if (hPipe != INVALID_HANDLE_VALUE)        {            std::string message("hello pip");            message += std::to_string(i);            message += "\n";            std::cout << "sending message:" << message << std::endl;            WriteFile(hPipe,                            //3,通过pip发送消息                message.c_str(),                message.size(),                 &bytesWritten,                NULL);            CloseHandle(hPipe);                         //4,关闭pip        }    }    return (0);}
0 0