popen.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // Copyright (c) 2022 Klemens D. Morgenstern
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_PROCESS_V2_POPEN_HPP
  6. #define BOOST_PROCESS_V2_POPEN_HPP
  7. #include <boost/process/v2/process.hpp>
  8. #include <boost/process/v2/stdio.hpp>
  9. #if defined(BOOST_PROCESS_V2_STANDALONE)
  10. #include <asio/connect_pipe.hpp>
  11. #include <asio/readable_pipe.hpp>
  12. #include <asio/writable_pipe.hpp>
  13. #else
  14. #include <boost/asio/connect_pipe.hpp>
  15. #include <boost/asio/readable_pipe.hpp>
  16. #include <boost/asio/writable_pipe.hpp>
  17. #endif
  18. BOOST_PROCESS_V2_BEGIN_NAMESPACE
  19. /// A subprocess with automatically assigned pipes.
  20. /** The purpose os the popen is to provide a convenient way
  21. * to use the stdin & stdout of a process.
  22. *
  23. * @code {.cpp}
  24. * popen proc(executor, find_executable("addr2line"), {argv[0]});
  25. * asio::write(proc, asio::buffer("main\n"));
  26. * std::string line;
  27. * asio::read_until(proc, asio::dynamic_buffer(line), '\n');
  28. * @endcode
  29. *
  30. *
  31. * Popen can be used as a stream object in other protocols.
  32. */
  33. template<typename Executor = BOOST_PROCESS_V2_ASIO_NAMESPACE::any_io_executor>
  34. struct basic_popen : basic_process<Executor>
  35. {
  36. /// The executor of the process
  37. using executor_type = Executor;
  38. /// Rebinds the popen type to another executor.
  39. template <typename Executor1>
  40. struct rebind_executor
  41. {
  42. /// The pipe type when rebound to the specified executor.
  43. typedef basic_popen<Executor1> other;
  44. };
  45. /// Move construct a popen
  46. basic_popen(basic_popen &&) = default;
  47. /// Move assign a popen
  48. basic_popen& operator=(basic_popen &&) = default;
  49. /// Move construct a popen and change the executor type.
  50. template<typename Executor1>
  51. basic_popen(basic_popen<Executor1>&& lhs)
  52. : basic_process<Executor>(std::move(lhs)),
  53. stdin_(std::move(lhs.stdin_)), stdout_(std::move(lhs.stdout_))
  54. {
  55. }
  56. /// Create a closed process handle
  57. explicit basic_popen(executor_type exec) : basic_process<Executor>{std::move(exec)} {}
  58. /// Create a closed process handle
  59. template <typename ExecutionContext>
  60. explicit basic_popen(ExecutionContext & context,
  61. typename std::enable_if<
  62. is_convertible<ExecutionContext&,
  63. BOOST_PROCESS_V2_ASIO_NAMESPACE::execution_context&>::value, void *>::type = nullptr)
  64. : basic_process<Executor>{context}
  65. {
  66. }
  67. /// Construct a child from a property list and launch it using the default process launcher.
  68. template<typename ... Inits>
  69. explicit basic_popen(
  70. executor_type executor,
  71. const filesystem::path& exe,
  72. std::initializer_list<string_view> args,
  73. Inits&&... inits)
  74. : basic_process<Executor>(executor)
  75. {
  76. this->basic_process<Executor>::operator=(
  77. default_process_launcher()(
  78. this->get_executor(), exe, args,
  79. std::forward<Inits>(inits)...,
  80. process_stdio{stdin_, stdout_}
  81. ));
  82. }
  83. /// Construct a child from a property list and launch it using the default process launcher.
  84. template<typename Launcher, typename ... Inits>
  85. explicit basic_popen(
  86. Launcher && launcher,
  87. executor_type executor,
  88. const filesystem::path& exe,
  89. std::initializer_list<string_view> args,
  90. Inits&&... inits)
  91. : basic_process<Executor>(executor)
  92. {
  93. this->basic_process<Executor>::operator=(
  94. std::forward<Launcher>(launcher)(
  95. this->get_executor(), exe, args,
  96. std::forward<Inits>(inits)...,
  97. process_stdio{stdin_, stdout_}
  98. ));
  99. }
  100. /// Construct a child from a property list and launch it using the default process launcher.
  101. template<typename Args, typename ... Inits>
  102. explicit basic_popen(
  103. executor_type executor,
  104. const filesystem::path& exe,
  105. Args&& args, Inits&&... inits)
  106. : basic_process<Executor>(executor)
  107. {
  108. this->basic_process<Executor>::operator=(
  109. default_process_launcher()(
  110. std::move(executor), exe, args,
  111. std::forward<Inits>(inits)...,
  112. process_stdio{stdin_, stdout_}
  113. ));
  114. }
  115. /// Construct a child from a property list and launch it using the default process launcher.
  116. template<typename Launcher, typename Args, typename ... Inits>
  117. explicit basic_popen(
  118. Launcher && launcher,
  119. executor_type executor,
  120. const filesystem::path& exe,
  121. Args&& args, Inits&&... inits)
  122. : basic_process<Executor>(executor)
  123. {
  124. this->basic_process<Executor>::operator=(
  125. std::forward<Launcher>(launcher)(
  126. std::move(executor), exe, args,
  127. std::forward<Inits>(inits)...,
  128. process_stdio{stdin_, stdout_}
  129. ));
  130. }
  131. /// Construct a child from a property list and launch it using the default process launcher.
  132. template<typename ExecutionContext, typename ... Inits>
  133. explicit basic_popen(
  134. ExecutionContext & context,
  135. typename std::enable_if<
  136. std::is_convertible<ExecutionContext&,
  137. BOOST_PROCESS_V2_ASIO_NAMESPACE::execution_context&>::value,
  138. const filesystem::path&>::type exe,
  139. std::initializer_list<string_view> args,
  140. Inits&&... inits)
  141. : basic_process<Executor>(context)
  142. {
  143. this->basic_process<Executor>::operator=(
  144. default_process_launcher()(
  145. this->get_executor(), exe, args,
  146. std::forward<Inits>(inits)...,
  147. process_stdio{stdin_, stdout_}
  148. ));
  149. }
  150. /// Construct a child from a property list and launch it using the default process launcher.
  151. template<typename Launcher, typename ExecutionContext, typename ... Inits>
  152. explicit basic_popen(
  153. Launcher && launcher,
  154. ExecutionContext & context,
  155. typename std::enable_if<
  156. std::is_convertible<ExecutionContext&,
  157. BOOST_PROCESS_V2_ASIO_NAMESPACE::execution_context&>::value,
  158. const filesystem::path&>::type exe,
  159. std::initializer_list<string_view> args,
  160. Inits&&... inits)
  161. : basic_process<Executor>(context)
  162. {
  163. this->basic_process<Executor>::operator=(
  164. std::forward<Launcher>(launcher)(
  165. this->get_executor(), exe, args,
  166. std::forward<Inits>(inits)...,
  167. process_stdio{stdin_, stdout_}
  168. ));
  169. }
  170. /// Construct a child from a property list and launch it using the default process launcher.
  171. template<typename ExecutionContext, typename Args, typename ... Inits>
  172. explicit basic_popen(
  173. ExecutionContext & context,
  174. typename std::enable_if<
  175. std::is_convertible<ExecutionContext&,
  176. BOOST_PROCESS_V2_ASIO_NAMESPACE::execution_context&>::value,
  177. const filesystem::path&>::type exe,
  178. Args&& args, Inits&&... inits)
  179. : basic_process<Executor>(context)
  180. {
  181. this->basic_process<Executor>::operator=(
  182. default_process_launcher()(
  183. this->get_executor(), exe, args,
  184. std::forward<Inits>(inits)...,
  185. process_stdio{stdin_, stdout_}
  186. ));
  187. }
  188. /// Construct a child from a property list and launch it using the default process launcher.
  189. template<typename Launcher, typename ExecutionContext, typename Args, typename ... Inits>
  190. explicit basic_popen(
  191. Launcher && launcher,
  192. ExecutionContext & context,
  193. typename std::enable_if<
  194. std::is_convertible<ExecutionContext&,
  195. BOOST_PROCESS_V2_ASIO_NAMESPACE::execution_context&>::value,
  196. const filesystem::path&>::type exe,
  197. Args&& args, Inits&&... inits)
  198. : basic_process<Executor>(context)
  199. {
  200. this->basic_process<Executor>::operator=(
  201. std::forward<Launcher>(launcher)(
  202. this->get_executor(), exe, args,
  203. std::forward<Inits>(inits)...,
  204. process_stdio{stdin_, stdout_}
  205. ));
  206. }
  207. /// The type used for stdin on the parent process side.
  208. using stdin_type = BOOST_PROCESS_V2_ASIO_NAMESPACE::basic_writable_pipe<Executor>;
  209. /// The type used for stdout on the parent process side.
  210. using stdout_type = BOOST_PROCESS_V2_ASIO_NAMESPACE::basic_readable_pipe<Executor>;
  211. /// Get the stdin pipe.
  212. stdin_type & get_stdin() {return stdin_; }
  213. /// Get the stdout pipe.
  214. stdout_type & get_stdout() {return stdout_; }
  215. /// Get the stdin pipe.
  216. const stdin_type & get_stdin() const {return stdin_; }
  217. /// Get the stdout pipe.
  218. const stdout_type & get_stdout() const {return stdout_; }
  219. /// Write some data to the pipe.
  220. /**
  221. * This function is used to write data to the pipe. The function call will
  222. * block until one or more bytes of the data has been written successfully,
  223. * or until an error occurs.
  224. *
  225. * @param buffers One or more data buffers to be written to the pipe.
  226. *
  227. * @returns The number of bytes written.
  228. *
  229. * @throws boost::system::system_error Thrown on failure. An error code of
  230. * boost::asio::error::eof indicates that the connection was closed by the
  231. * subprocess.
  232. *
  233. * @note The write_some operation may not transmit all of the data to the
  234. * peer. Consider using the @ref write function if you need to ensure that
  235. * all data is written before the blocking operation completes.
  236. *
  237. * @par Example
  238. * To write a single data buffer use the @ref buffer function as follows:
  239. * @code
  240. * pipe.write_some(boost::asio::buffer(data, size));
  241. * @endcode
  242. * See the @ref buffer documentation for information on writing multiple
  243. * buffers in one go, and how to use it with arrays, boost::array or
  244. * std::vector.
  245. */
  246. template <typename ConstBufferSequence>
  247. std::size_t write_some(const ConstBufferSequence& buffers)
  248. {
  249. return stdin_.write_some(buffers);
  250. }
  251. /// Write some data to the pipe.
  252. /**
  253. * This function is used to write data to the pipe. The function call will
  254. * block until one or more bytes of the data has been written successfully,
  255. * or until an error occurs.
  256. *
  257. * @param buffers One or more data buffers to be written to the pipe.
  258. *
  259. * @param ec Set to indicate what error occurred, if any.
  260. *
  261. * @returns The number of bytes written. Returns 0 if an error occurred.
  262. *
  263. * @note The write_some operation may not transmit all of the data to the
  264. * subprocess. Consider using the @ref write function if you need to ensure that
  265. * all data is written before the blocking operation completes.
  266. */
  267. template <typename ConstBufferSequence>
  268. std::size_t write_some(const ConstBufferSequence& buffers,
  269. boost::system::error_code& ec)
  270. {
  271. return stdin_.write_some(buffers, ec);
  272. }
  273. /// Start an asynchronous write.
  274. /**
  275. * This function is used to asynchronously write data to the pipe. It is an
  276. * initiating function for an @ref asynchronous_operation, and always returns
  277. * immediately.
  278. *
  279. * @param buffers One or more data buffers to be written to the pipe.
  280. * Although the buffers object may be copied as necessary, ownership of the
  281. * underlying memory blocks is retained by the caller, which must guarantee
  282. * that they remain valid until the completion handler is called.
  283. *
  284. * @param token The @ref completion_token that will be used to produce a
  285. * completion handler, which will be called when the write completes.
  286. * Potential completion tokens include @ref use_future, @ref use_awaitable,
  287. * @ref yield_context, or a function object with the correct completion
  288. * signature. The function signature of the completion handler must be:
  289. * @code void handler(
  290. * const boost::system::error_code& error, // Result of operation.
  291. * std::size_t bytes_transferred // Number of bytes written.
  292. * ); @endcode
  293. * Regardless of whether the asynchronous operation completes immediately or
  294. * not, the completion handler will not be invoked from within this function.
  295. * On immediate completion, invocation of the handler will be performed in a
  296. * manner equivalent to using boost::asio::post().
  297. *
  298. * @par Completion Signature
  299. * @code void(boost::system::error_code, std::size_t) @endcode
  300. *
  301. * @note The write operation may not transmit all of the data to the peer.
  302. * Consider using the @ref async_write function if you need to ensure that all
  303. * data is written before the asynchronous operation completes.
  304. *
  305. * @par Example
  306. * To write a single data buffer use the @ref buffer function as follows:
  307. * @code
  308. * popen.async_write_some(boost::asio::buffer(data, size), handler);
  309. * @endcode
  310. * See the @ref buffer documentation for information on writing multiple
  311. * buffers in one go, and how to use it with arrays, boost::array or
  312. * std::vector.
  313. */
  314. template <typename ConstBufferSequence,
  315. BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code,
  316. std::size_t)) WriteToken
  317. BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
  318. BOOST_PROCESS_V2_INITFN_AUTO_RESULT_TYPE(WriteToken,
  319. void (boost::system::error_code, std::size_t))
  320. async_write_some(const ConstBufferSequence& buffers,
  321. BOOST_ASIO_MOVE_ARG(WriteToken) token
  322. BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(executor_type))
  323. {
  324. return stdin_.async_write_some(buffers, std::forward<WriteToken>(token));
  325. }
  326. /// Read some data from the pipe.
  327. /**
  328. * This function is used to read data from the pipe. The function call will
  329. * block until one or more bytes of data has been read successfully, or until
  330. * an error occurs.
  331. *
  332. * @param buffers One or more buffers into which the data will be read.
  333. *
  334. * @returns The number of bytes read.
  335. *
  336. * @throws boost::system::system_error Thrown on failure. An error code of
  337. * boost::asio::error::eof indicates that the connection was closed by the
  338. * peer.
  339. *
  340. * @note The read_some operation may not read all of the requested number of
  341. * bytes. Consider using the @ref read function if you need to ensure that
  342. * the requested amount of data is read before the blocking operation
  343. * completes.
  344. *
  345. * @par Example
  346. * To read into a single data buffer use the @ref buffer function as follows:
  347. * @code
  348. * basic_readable_pipe.read_some(boost::asio::buffer(data, size));
  349. * @endcode
  350. * See the @ref buffer documentation for information on reading into multiple
  351. * buffers in one go, and how to use it with arrays, boost::array or
  352. * std::vector.
  353. */
  354. template <typename MutableBufferSequence>
  355. std::size_t read_some(const MutableBufferSequence& buffers)
  356. {
  357. return stdout_.read_some(buffers);
  358. }
  359. /// Read some data from the pipe.
  360. /**
  361. * This function is used to read data from the pipe. The function call will
  362. * block until one or more bytes of data has been read successfully, or until
  363. * an error occurs.
  364. *
  365. * @param buffers One or more buffers into which the data will be read.
  366. *
  367. * @param ec Set to indicate what error occurred, if any.
  368. *
  369. * @returns The number of bytes read. Returns 0 if an error occurred.
  370. *
  371. * @note The read_some operation may not read all of the requested number of
  372. * bytes. Consider using the @ref read function if you need to ensure that
  373. * the requested amount of data is read before the blocking operation
  374. * completes.
  375. */
  376. template <typename MutableBufferSequence>
  377. std::size_t read_some(const MutableBufferSequence& buffers,
  378. boost::system::error_code& ec)
  379. {
  380. return stdout_.read_some(buffers, ec);
  381. }
  382. /// Start an asynchronous read.
  383. /**
  384. * This function is used to asynchronously read data from the pipe. It is an
  385. * initiating function for an @ref asynchronous_operation, and always returns
  386. * immediately.
  387. *
  388. * @param buffers One or more buffers into which the data will be read.
  389. * Although the buffers object may be copied as necessary, ownership of the
  390. * underlying memory blocks is retained by the caller, which must guarantee
  391. * that they remain valid until the completion handler is called.
  392. *
  393. * @param token The @ref completion_token that will be used to produce a
  394. * completion handler, which will be called when the read completes.
  395. * Potential completion tokens include @ref use_future, @ref use_awaitable,
  396. * @ref yield_context, or a function object with the correct completion
  397. * signature. The function signature of the completion handler must be:
  398. * @code void handler(
  399. * const boost::system::error_code& error, // Result of operation.
  400. * std::size_t bytes_transferred // Number of bytes read.
  401. * ); @endcode
  402. * Regardless of whether the asynchronous operation completes immediately or
  403. * not, the completion handler will not be invoked from within this function.
  404. * On immediate completion, invocation of the handler will be performed in a
  405. * manner equivalent to using boost::asio::post().
  406. *
  407. * @par Completion Signature
  408. * @code void(boost::system::error_code, std::size_t) @endcode
  409. *
  410. * @note The read operation may not read all of the requested number of bytes.
  411. * Consider using the @ref async_read function if you need to ensure that the
  412. * requested amount of data is read before the asynchronous operation
  413. * completes.
  414. *
  415. * @par Example
  416. * To read into a single data buffer use the @ref buffer function as follows:
  417. * @code
  418. * basic_readable_pipe.async_read_some(
  419. * boost::asio::buffer(data, size), handler);
  420. * @endcode
  421. * See the @ref buffer documentation for information on reading into multiple
  422. * buffers in one go, and how to use it with arrays, boost::array or
  423. * std::vector.
  424. */
  425. template <typename MutableBufferSequence,
  426. BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code,
  427. std::size_t)) ReadToken
  428. BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
  429. BOOST_PROCESS_V2_INITFN_AUTO_RESULT_TYPE(ReadToken,
  430. void (boost::system::error_code, std::size_t))
  431. async_read_some(const MutableBufferSequence& buffers,
  432. BOOST_ASIO_MOVE_ARG(ReadToken) token
  433. BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(executor_type))
  434. {
  435. return stdout_.async_read_some(buffers, std::forward<ReadToken>(token));
  436. }
  437. private:
  438. stdin_type stdin_ {basic_process<Executor>::get_executor()};
  439. stdout_type stdout_{basic_process<Executor>::get_executor()};
  440. };
  441. /// A popen object with the default executor.
  442. using popen = basic_popen<>;
  443. BOOST_PROCESS_V2_END_NAMESPACE
  444. #endif //BOOST_PROCESS_V2_POPEN_HPP