Search code examples
c++boostforkboost-asiodup2

Similar functionality to dup2 in boost


I would like to do some thing like this

acceptSocket = accept(...);
if (fork() == 0) {
  // ..
  dup2(acceptSocket, 1);
  dup2(acceptSocket, 2);
  execvp(/*some command*/);
  
}

Now I’m moving to C++ boost and I would like to do the same thing. Is there anything similar to this? Probably it would be Boost Process and socket stream but I couldn’t quite figure out. Thanks in advance.


Solution

  • You can use Boost Process: https://www.boost.org/doc/libs/1_74_0/doc/html/boost/process/posix/fd.html

    This property lets you modify file-descriptors other than the standard ones (0,1,2).

    It provides the functions bind, which implements dup2 and close.

    So, example:

    #include <boost/process.hpp>
    
    namespace bp = boost::process;
    using bp::posix::fd;
    
    int main() {
        int acceptSocket /* = accept(...) */;
    
        bp::child child(
            bp::search_path("someprogram.exe"),
            fd.bind(1, acceptSocket),
            fd.bind(2, acceptSocket));
    
        child.wait();
    }