pipe_in.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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_POSIX_PIPE_IN_HPP
  10. #define BOOST_PROCESS_POSIX_PIPE_IN_HPP
  11. #include <boost/process/pipe.hpp>
  12. #include <boost/process/detail/posix/handler.hpp>
  13. #include <unistd.h>
  14. #include <boost/process/detail/used_handles.hpp>
  15. #include <array>
  16. namespace boost { namespace process { namespace detail { namespace posix {
  17. struct pipe_in : handler_base_ext, ::boost::process::detail::uses_handles
  18. {
  19. int source;
  20. int sink; //opposite end
  21. pipe_in(int sink, int source) : source(source), sink(sink) {}
  22. std::array<int, 3> get_used_handles()
  23. {
  24. return {{STDIN_FILENO, source, sink}};
  25. }
  26. template<typename T>
  27. pipe_in(T & p) : source(p.native_source()), sink(p.native_sink())
  28. {
  29. p.assign_source(-1);
  30. }
  31. template<typename Executor>
  32. void on_error(Executor &, const std::error_code &) const
  33. {
  34. ::close(source);
  35. }
  36. template<typename Executor>
  37. void on_success(Executor &) const
  38. {
  39. ::close(source);
  40. }
  41. template <class Executor>
  42. void on_exec_setup(Executor &e) const
  43. {
  44. if (::dup2(source, STDIN_FILENO) == -1)
  45. e.set_error(::boost::process::detail::get_last_error(), "dup2() failed");
  46. if (source != STDIN_FILENO)
  47. ::close(source);
  48. ::close(sink);
  49. }
  50. };
  51. class async_pipe;
  52. struct async_pipe_in : public pipe_in
  53. {
  54. async_pipe &pipe;
  55. template<typename AsyncPipe>
  56. async_pipe_in(AsyncPipe & p) : pipe_in(p.native_sink(), p.native_source()), pipe(p)
  57. {
  58. }
  59. template<typename Pipe, typename Executor>
  60. static void close(Pipe & pipe, Executor &)
  61. {
  62. boost::system::error_code ec;
  63. std::move(pipe).source().close(ec);
  64. }
  65. template<typename Executor>
  66. void on_error(Executor & exec, const std::error_code &)
  67. {
  68. close(pipe, exec);
  69. }
  70. template<typename Executor>
  71. void on_success(Executor &exec)
  72. {
  73. close(pipe, exec);
  74. }
  75. };
  76. }}}}
  77. #endif