【问题标题】:Connect with an already created named pipe with boost使用 boost 连接已创建的命名管道
【发布时间】:2020-08-25 23:34:03
【问题描述】:

我正在考虑使用第三方库在Windows 上使用named pipes 进行IPC 通信。在过去的几年里,我一直在使用Win32API。我有兴趣用一个久经考验的真正开源库替换我的实现。

我注意到boost::process 有一个async_pipe 的实现,它允许我将它与boost::asio 一起使用,这对我的应用程序非常有帮助。

我要做的是在服务器上创建named pipe,这是一个C# 应用程序。 创建pipe 后,使用boost::process::async_pipe 与客户端连接。

我遇到的问题是我在boost::process 中没有看到允许我连接到已经创建的named pipe 的API。 constructorsasync_pipe 创建 pipe 而不是连接到已创建的 pipe

下面是我当前在客户端中使用的代码,它错误地创建了pipe

boost::asio::io_context ctx;
std::vector<char> buffer( 8196, 0 );

boost::process::async_pipe pipe{ ctx, R"(\\.\pipe\TestPipe)" }; 

boost::asio::async_read( pipe, boost::asio::buffer( buffer ),
    [ &buffer ]( const boost::system::error_code& ec, std::size_t size )
    {
        if ( ec )
            std::cout << "Error: " << ec.message( ) << '\n';
        else
        {
            std::string message{ std::begin( buffer ), std::begin( buffer ) + size };
            std::cout << "Received message: " << message << '\n';
        }
    } );

ctx.run( );

我不确定是否可以使用boost::process 来实现我想要的。我想知道是否有一种方法可以使用CreateFileWnamed pipe 连接,然后将HANDLE 传递给async_pipe,但我还没有找到任何相关文档。

问题

如何使用boost 连接已创建的named pipe

【问题讨论】:

  • 要连接到已经创建的命名管道,您只需调用 CreateFileWasync_pipe 是做什么的,对于异步 i/o 来说,它到底是怎么回事?

标签: c++ windows boost ipc


【解决方案1】:

好的,所以我做错了。 在 Github Link 上阅读此问题后,我意识到我需要改用 stream_handle。注意,pipe 必须在 OVERLAPPED 模式下打开才能工作。

创建stream_handle

static boost::asio::windows::stream_handle OpenPipe( io_context& context )
{
    constexpr const wchar_t* pipeName{ LR"(\\.\pipe\TestPipe)" };
    return { context, CreateFileW( pipeName,
                                   GENERIC_READ | GENERIC_WRITE,
                                   0, nullptr,
                                   OPEN_EXISTING,
                                   FILE_FLAG_OVERLAPPED,
                                   nullptr ) };
}

创建stream_handle 后,您可以使用它提供的async 函数进行通信。

使用stream_handle

std::vector<char> buffer( 8196, 0 );
pipe.async_read_some( boost::asio::buffer( buffer ), 
    [ &buffer ]( auto ec, auto size ) { } );

【讨论】:

  • 我可以知道pipe 是什么类型吗?我可以让它通过boost::asio::windows::stream_handle(OpenPipe(pipe_context)).async_read_some(boost::asio::buffer(buffer), [&amp;buffer](auto ec, auto size) {}); 成功读取,但我需要一步一步运行,否则总是失败...我需要分离这段代码...
  • @VannesYang OpenPipe 函数通过aggregate initialization 创建一个stream_handle。例如,如果您想在 main 中创建管道,请执行以下操作:stream_handle sh{ context, CreateFileW( pipeName, ... ) };
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-11
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
相关资源
最近更新 更多