file_out.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // Copyright (c) 2016 Klemens D. Morgenstern
  7. //
  8. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. #ifndef BOOST_PROCESS_POSIX_FILE_OUT_HPP
  11. #define BOOST_PROCESS_POSIX_FILE_OUT_HPP
  12. #include <boost/process/detail/posix/handler.hpp>
  13. #include <boost/process/detail/posix/file_descriptor.hpp>
  14. #include <boost/process/detail/used_handles.hpp>
  15. #include <unistd.h>
  16. namespace boost { namespace process { namespace detail { namespace posix {
  17. template<int p1, int p2>
  18. struct file_out : handler_base_ext, ::boost::process::detail::uses_handles
  19. {
  20. file_descriptor file;
  21. int handle = file.handle();
  22. template<typename T>
  23. file_out(T&& t) : file(std::forward<T>(t), file_descriptor::write), handle(file.handle()) {}
  24. file_out(FILE * f) : handle(fileno(f)) {}
  25. std::array<int, 3> get_used_handles()
  26. {
  27. const auto pp1 = p1 != -1 ? p1 : p2;
  28. const auto pp2 = p2 != -1 ? p2 : p1;
  29. return {handle, pp1, pp2};
  30. }
  31. template <typename Executor>
  32. void on_exec_setup(Executor &e) const;
  33. };
  34. template<>
  35. template<typename Executor>
  36. void file_out<1,-1>::on_exec_setup(Executor &e) const
  37. {
  38. if (::dup2(handle, STDOUT_FILENO) == -1)
  39. e.set_error(::boost::process::detail::get_last_error(), "dup2() failed");
  40. }
  41. template<>
  42. template<typename Executor>
  43. void file_out<2,-1>::on_exec_setup(Executor &e) const
  44. {
  45. if (::dup2(handle, STDERR_FILENO) == -1)
  46. e.set_error(::boost::process::detail::get_last_error(), "dup2() failed");
  47. }
  48. template<>
  49. template<typename Executor>
  50. void file_out<1,2>::on_exec_setup(Executor &e) const
  51. {
  52. if (::dup2(handle, STDOUT_FILENO) == -1)
  53. e.set_error(::boost::process::detail::get_last_error(), "dup2() failed");
  54. if (::dup2(handle, STDERR_FILENO) == -1)
  55. e.set_error(::boost::process::detail::get_last_error(), "dup2() failed");
  56. }
  57. }}}}
  58. #endif