Search code examples
c++boostboost-process

Create child process with custom environment using boost


The documentation boost doesn't provide any example for creating a child process with a custom environment using process::child(...).
An example is given with process::system(...) but the function system has less possible operations (such as pipes or waitpid) so I would like to have a full example using process::child if possible.


Solution

  • in system.hpp, system_impl, which supports custom env, is implemented in terms of 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();
    }
    

    So the call to system from the docs:

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

    which calls:

    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)...);
    }
    

    translates into this function, so you should be able to do the same.