fd.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright (c) 2006, 2007 Julio M. Merino Vidal
  2. // Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
  3. // Copyright (c) 2009 Boris Schaeling
  4. // Copyright (c) 2010 Felipe Tanus, Boris Schaeling
  5. // Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. #ifndef BOOST_PROCESS_DETAIL_POSIX_FD_HPP
  10. #define BOOST_PROCESS_DETAIL_POSIX_FD_HPP
  11. #include <boost/process/detail/posix/handler.hpp>
  12. #include <unistd.h>
  13. namespace boost { namespace process { namespace detail { namespace posix {
  14. struct close_fd_ : handler_base_ext
  15. {
  16. close_fd_(int fd) : fd_(fd) {}
  17. template <class PosixExecutor>
  18. void on_exec_setup(PosixExecutor& e) const
  19. {
  20. if (::close(fd_) == -1)
  21. e.set_error(::boost::process::detail::get_last_error(), "close() failed");
  22. }
  23. private:
  24. int fd_;
  25. };
  26. template <class Range>
  27. struct close_fds_ : handler_base_ext
  28. {
  29. public:
  30. close_fds_(const Range &fds) : fds_(fds) {}
  31. template <class PosixExecutor>
  32. void on_exec_setup(PosixExecutor& e) const
  33. {
  34. for (auto & fd_ : fds_)
  35. if (::close(fd_) == -1)
  36. {
  37. e.set_error(::boost::process::detail::get_last_error(), "close() failed");
  38. break;
  39. }
  40. }
  41. private:
  42. Range fds_;
  43. };
  44. template <class FileDescriptor>
  45. struct bind_fd_ : handler_base_ext
  46. {
  47. public:
  48. bind_fd_(int id, const FileDescriptor &fd) : id_(id), fd_(fd) {}
  49. template <class PosixExecutor>
  50. void on_exec_setup(PosixExecutor& e) const
  51. {
  52. if (::dup2(fd_, id_) == -1)
  53. e.set_error(::boost::process::detail::get_last_error(), "dup2() failed");
  54. }
  55. private:
  56. int id_;
  57. FileDescriptor fd_;
  58. };
  59. struct fd_
  60. {
  61. constexpr fd_() {};
  62. close_fd_ close(int _fd) const {return close_fd_(_fd);}
  63. close_fds_<std::vector<int>> close(const std::initializer_list<int> & vec) const {return std::vector<int>(vec);}
  64. template<typename Range>
  65. close_fds_<Range> close(const Range & r) const {return r;}
  66. template <class FileDescriptor>
  67. bind_fd_<FileDescriptor> bind(int id, const FileDescriptor & fd) const {return {id, fd};}
  68. };
  69. }}}}
  70. #endif