使用 boost 创建具有自定义环境的子进程

zac*_*ein 5 c++ boost boost-process

文档提升没有提供任何使用自定义环境创建子进程的示例process::child(...)
给出了一个示例,process::system(...)但该函数的system可能操作较少(例如管道或 waitpid),因此如果可能的话,我希望有一个完整的示例process::child

xax*_*xon 0

system.hpp中,system_impl,支持自定义env,以child的方式实现,

template<typename IoService, typename ...Args>
inline int system_impl(
        std::true_type, /*needs ios*/
        std::true_type, /*has io_context*/
        Args && ...args)
{
    IoService & ios = ::boost::process::detail::get_io_context_var(args...);

    system_impl_success_check check;

    std::atomic_bool exited{false};

    child c(std::forward<Args>(args)...,
            check,
            ::boost::process::on_exit(
                [&](int, const std::error_code&)
                {
                    ios.post([&]{exited.store(true);});
                }));
    if (!c.valid() || !check.succeeded)
        return -1;

    while (!exited.load())
        ios.poll();

    return c.exit_code();
}
Run Code Online (Sandbox Code Playgroud)

所以从文档中调用系统:

bp::system("stuff", bp::env["VALUE_1"]="foo", bp::env["VALUE_2"]+={"bar1", "bar2"});
Run Code Online (Sandbox Code Playgroud)

其中调用:

template<typename ...Args>
inline int system(Args && ...args)
{
    typedef typename ::boost::process::detail::needs_io_context<Args...>::type
            need_ios;
    typedef typename ::boost::process::detail::has_io_context<Args...>::type
            has_ios;
    return ::boost::process::detail::system_impl<boost::asio::io_context>(
            need_ios(), has_ios(),
            std::forward<Args>(args)...);
}
Run Code Online (Sandbox Code Playgroud)

翻译成这个函数,所以你应该能够做同样的事情。