繁体   English   中英

通过 boost 连接已创建的名为 pipe

[英]Connect with an already created named pipe with boost

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

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

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

我遇到的问题是我在boost::process中看不到 API ,这将允许我连接已创建的named pipe async_pipeconstructors函数创建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

好的,所以我走错了路。 在 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 ) { } );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM