tutorial.qbk 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. [def bp::system [funcref boost::process::system bp::system]]
  2. [def bp::async_system [funcref boost::process::async_system bp::async_system]]
  3. [def bp::spawn [funcref boost::process::spawn bp::spawn]]
  4. [def bp::child [classref boost::process::child bp::child]]
  5. [def bp::cmd [classref boost::process::cmd bp::cmd]]
  6. [def bp::group [classref boost::process::group bp::group]]
  7. [def bp::ipstream [classref boost::process::ipstream bp::ipstream]]
  8. [def bp::opstream [classref boost::process::opstream bp::opstream]]
  9. [def bp::pstream [classref boost::process::pstream bp::pstream]]
  10. [def bp::pipe [classref boost::process::pipe bp::pipe]]
  11. [def bp::async_pipe [classref boost::process::async_pipe bp::async_pipe]]
  12. [def bp::search_path [funcref boost::process::search_path bp::search_path]]
  13. [def boost_org [@www.boost.org "www.boost.org"]]
  14. [def std::system [@http://en.cppreference.com/w/cpp/utility/program/system std::system]]
  15. [def child_running [memberref boost::process::child::running running]]
  16. [def child_wait [memberref boost::process::child::wait wait]]
  17. [def child_wait_for [memberref boost::process::child::wait_for wait_for]]
  18. [def child_exit_code [memberref boost::process::child::exit_code exit_code]]
  19. [def group_wait_for [memberref boost::process::group::wait_for wait_for]]
  20. [def bp::on_exit [globalref boost::process::on_exit bp::on_exit]]
  21. [def bp::null [globalref boost::process::null bp::null]]
  22. [def child_terminate [memberref boost::process::child::terminate terminate]]
  23. [def group_terminate [memberref boost::process::group::terminate terminate]]
  24. [def group_wait [memberref boost::process::group::wait wait]]
  25. [def bp::std_in [globalref boost::process::std_in bp::std_in]]
  26. [def bp::std_out [globalref boost::process::std_out bp::std_out]]
  27. [def bp::std_err [globalref boost::process::std_err bp::std_err]]
  28. [def io_service [@http://www.boost.org/doc/libs/release/doc/html/boost_asio/reference/io_service.html boost::asio::io_service]]
  29. [def asio_buffer [@http://www.boost.org/doc/libs/release/doc/html/boost_asio/reference/buffer.html boost::asio::buffer]]
  30. [def asio_async_read [@http://www.boost.org/doc/libs/release/doc/html/boost_asio/reference/async_read.html boost::asio::async_read]]
  31. [def bp::environment [classref boost::process::basic_environment bp::environment]]
  32. [def bp::native_environment [classref boost::process::basic_native_environment bp::native_environment]]
  33. [def boost::this_process::environment [funcref boost::this_process::environment boost::this_process:deadlock :environment]]
  34. [def std::chrono::seconds [@http://en.cppreference.com/w/cpp/chrono/duration std::chrono::seconds]]
  35. [def std::vector [@http://en.cppreference.com/w/cpp/container/vector std::vector]]
  36. [def __wait_for__ [memberref boost::process::child::wait_for wait_for]]
  37. [def __wait_until__ [memberref boost::process::child::wait_until wait_until]]
  38. [def __detach__ [memberref boost::process::child::detach detach]]
  39. [def __reference__ [link process.reference reference]]
  40. [def __concepts__ [link boost_process.concepts concepts]]
  41. [def boost::asio::yield_context [@http://www.boost.org/doc/libs/release/doc/html/boost_asio/reference/yield_context.html boost::asio::yield_context]]
  42. [def boost::asio::coroutine [@http://www.boost.org/doc/libs/release/doc/html/boost_asio/reference/coroutine.html boost::asio::coroutine]]
  43. [def bp::env [globalref boost::process::env bp::env]]
  44. [section:tutorial Tutorial]
  45. In this section we will go step by step through the different features of
  46. boost.process. For a full description see the __reference__ and the __concepts__ sections.
  47. [section Starting a process]
  48. We want to start a process, so let's start with a simple process. We will
  49. invoke the gcc compiler to compile a simple program.
  50. With the standard library this looks like this.
  51. ```
  52. int result = std::system("g++ main.cpp");
  53. ```
  54. Which we can write exactly like this in boost.process.
  55. ```
  56. namespace bp = boost::process; //we will assume this for all further examples
  57. int result = bp::system("g++ main.cpp");
  58. ```
  59. If a single string (or the explicit form bp::cmd), it will be interpreted as a command line.
  60. That will cause the execution function to search the `PATH` variable to find the executable.
  61. The alternative is the `exe-args` style, where the first string will be interpreted as a filename (including the path),
  62. and the rest as arguments passed to said function.
  63. [note For more details on the `cmd`/`exe-args` style look [link boost_process.design.arg_cmd_style here]]
  64. So as a first step, we'll use the `exe-args` style.
  65. ```
  66. int result = bp::system("/usr/bin/g++", "main.cpp");
  67. ```
  68. With that syntax we still have "g++" hard-coded, so let's assume we get the string
  69. from an external source as `boost::filesystem::path`, we can do this too.
  70. ```
  71. boost::filesystem::path p = "/usr/bin/g++"; //or get it from somewhere else.
  72. int result = bp::system(p, "main.cpp");
  73. ```
  74. Now we might want to find the `g++` executable in the `PATH`-variable, as the `cmd` syntax would do.
  75. `Boost.process` provides a function to this end: bp::search_path.
  76. ```
  77. boost::filesystem::path p = bp::search_path("g++"); //or get it from somewhere else.
  78. int result = bp::system(p, "main.cpp");
  79. ```
  80. [note [funcref boost::process::search_path search_path] will search for any executable with that name.
  81. This also includes to add a file suffix on windows, such as `.exe` or `.bat`.]
  82. [endsect]
  83. [section:launch_mode Launch functions]
  84. Given that our example used the [funcref boost::process::system system] function,
  85. our program will wait until the child process is completed. This may be unwanted,
  86. especially since compiling can take a while.
  87. In order to avoid that, boost.process provides several ways to launch a process.
  88. Besides the already mentioned [funcref boost::process::system system] function and its
  89. asynchronous version [funcref boost::process::async_system async_system],
  90. we can also use the [funcref boost::process::spawn spawn] function or the
  91. [classref boost::process::child child] class.
  92. The [funcref boost::process::spawn spawn] function launches a process and
  93. immediately detaches it, so no handle will be returned and the process will be ignored.
  94. This is not what we need for compiling, but maybe we want to entertain the user,
  95. while compiling:
  96. ```
  97. bp::spawn(bp::search_path("chrome"), boost_org);
  98. ```
  99. Now for the more sensible approach for compiling: a non-blocking execution.
  100. To implement that, we directly call the constructor of [classref boost::process::child child].
  101. ```
  102. bp::child c(bp::search_path("g++"), "main.cpp");
  103. while (c.child_running())
  104. do_some_stuff();
  105. c.child_wait(); //wait for the process to exit
  106. int result = c.child_exit_code();
  107. ```
  108. So we launch the process, by calling the child constructor. Then we check and do other
  109. things while the process is running and afterwards get the exit code. The call
  110. to child_wait is necessary, to obtain it and tell the operating system, that no
  111. one is waiting for the process anymore.
  112. [note You can also wait for a time span or a until a time point with __wait_for__ and __wait_until__]
  113. [warning If you don't call wait on a child object, it will be terminated on destruction.
  114. This can be avoided by calling __detach__ beforehand]
  115. [endsect]
  116. [section:error_handling Error]
  117. Until now, we have assumed that everything works out, but it is not impossible,
  118. that "g++" is not present. That will cause the launch of the process to fail.
  119. The default behaviour of all functions is to throw a
  120. [@http://en.cppreference.com/w/cpp/error/system_error std::system_error] on failure.
  121. As with many other functions in this library, passing an [@http://en.cppreference.com/w/cpp/error/error_code std::error_code]
  122. will change the behaviour, so that instead of throwing an exception, the error will be assigned to the error code.
  123. ```
  124. std::error_code ec;
  125. bp::system("g++ main.cpp", ec);
  126. ```
  127. [endsect]
  128. [section:io Synchronous I/O]
  129. In the examples given above, we have only started a program, but did not consider the output.
  130. The default depends on the system, but usually this will just write it to the same output as the launching process.
  131. If this shall be guaranteed, the streams can be explicitly forwarded like this.
  132. ```
  133. bp::system("g++ main.cpp", bp::std_out > stdout, bp::std_err > stderr, bp::std_in < stdin);
  134. ```
  135. Now for the first example, we might want to just ignore the output, which can be done by redirecting it to the null-device.
  136. This can be achieved this way:
  137. ```
  138. bp::system("g++ main.cpp", bp::std_out > bp::null);
  139. ```
  140. Alternatively we can also easily redirect the output to a file:
  141. ```
  142. bp::system("g++ main.cpp", bp::std_out > "gcc_out.log");
  143. ```
  144. Now, let's take a more visual example for reading data.
  145. [@http://pubs.opengroup.org/onlinepubs/009696699/utilities/nm.html nm] is a tool on posix,
  146. which reads the outline, i.e. a list of all entry points, of a binary.
  147. Every entry point will be put into a single line, and we will use a pipe to read it.
  148. At the end an empty line is appended, which we use as the indication to stop reading.
  149. Boost.process provides the pipestream ([classref boost::process::ipstream ipstream],
  150. [classref boost::process::opstream opstream], [classref boost::process::pstream pstream]) to
  151. wrap around the [classref boost::process::pipe pipe] and provide an implementation of the
  152. [@http://en.cppreference.com/w/cpp/io/basic_istream std::istream],
  153. [@http://en.cppreference.com/w/cpp/io/basic_ostream std::ostream] and
  154. [@http://en.cppreference.com/w/cpp/io/basic_iostream std::iostream] interface.
  155. ```
  156. std::vector<std::string> read_outline(std::string & file)
  157. {
  158. bp::ipstream is; //reading pipe-stream
  159. bp::child c(bp::search_path("nm"), file, bp::std_out > is);
  160. std::vector<std::string> data;
  161. std::string line;
  162. while (c.child_running() && std::getline(is, line) && !line.empty())
  163. data.push_back(line);
  164. c.child_wait();
  165. return data;
  166. }
  167. ```
  168. What this does is redirect the `stdout` of the process into a pipe and we read this
  169. synchronously.
  170. [note You can do the same thing with [globalref boost::process::std_err std_err]]
  171. Now we get the name from `nm` and we might want to demangle it, so we use input and output.
  172. `nm` has a demangle option, but for the sake of the example, we'll use
  173. [@https://sourceware.org/binutils/docs/binutils/c_002b_002bfilt.html c++filt] for this.
  174. ```
  175. bp::opstream in;
  176. bp::ipstream out;
  177. bp::child c("c++filt", std_out > out, std_in < in);
  178. in << "_ZN5boost7process8tutorialE" << endl;
  179. std::string value;
  180. out >> value;
  181. c.child_terminate();
  182. ```
  183. Now you might want to forward output from one process to another processes input.
  184. ```
  185. std::vector<std::string> read_demangled_outline(const std::string & file)
  186. {
  187. bp::pipe p;
  188. bp::ipstream is;
  189. std::vector<std::string> outline;
  190. //we just use the same pipe, so the
  191. bp::child nm(bp::search_path("nm"), file, bp::std_out > p);
  192. bp::child filt(bp::search_path("c++filt"), bp::std_in < p, bp::std_out > is);
  193. std::string line;
  194. while (filt.running() && std::getline(is, line)) //when nm finished the pipe closes and c++filt exits
  195. outline.push_back(line);
  196. nm.child_wait();
  197. filt.wait();
  198. }
  199. ```
  200. This forwards the data from `nm` to `c++filt` without your process needing to do anything.
  201. [endsect]
  202. [section:async_io Asynchronous I/O]
  203. Boost.process allows the usage of boost.asio to implement asynchronous I/O.
  204. If you are familiar with [@http://www.boost.org/doc/libs/release/libs/asio/ boost.asio] (which we highly recommend),
  205. you can use [classref boost::process::async_pipe async_pipe] which is implemented
  206. as an I/O-Object and can be used like [classref boost::process::pipe pipe] as shown above.
  207. Now we get back to our compiling example. `nm` we might analyze it line by line,
  208. but the compiler output will just be put into one large buffer.
  209. With [@http://www.boost.org/doc/libs/release/libs/asio/ boost.asio] this is what it looks like.
  210. ```
  211. io_service ios;
  212. std::vector<char> buf(4096);
  213. bp::async_pipe ap(ios);
  214. bp::child c(bp::search_path("g++"), "main.cpp", bp::std_out > ap);
  215. asio_async_read(ap, asio_buffer(buf),
  216. [](const boost::system::error_code &ec, std::size_t size){});
  217. ios.run();
  218. int result = c.exit_code();
  219. ```
  220. To make it easier, boost.process provides simpler interface for that, so that the buffer can be passed directly,
  221. provided we also pass a reference to an io_service.
  222. ```
  223. io_service ios;
  224. std::vector<char> buf(4096);
  225. bp::child c(bp::search_path("g++"), "main.cpp", bp::std_out > asio_buffer(buf), ios);
  226. ios.run();
  227. int result = c.exit_code();
  228. ```
  229. [note Passing an instance of io_service to the launching function automatically cause it to wait asynchronously for the exit, so no call of
  230. [memberref boost::process::child::wait wait] is needed]
  231. To make it even easier, you can use [@http://en.cppreference.com/w/cpp/thread/future std::future] for asynchronous operations
  232. (you will still need to pass a reference to a io_service) to the launching function, unless you use bp::system or bp::async_system.
  233. Now we will revisit our first example and read the compiler output asynchronously:
  234. ```
  235. boost::asio::io_service ios;
  236. std::future<std::string> data;
  237. child c("g++", "main.cpp", //set the input
  238. bp::std_in.close(),
  239. bp::std_out > bp::null, //so it can be written without anything
  240. bp::std_err > data,
  241. ios);
  242. ios.run(); //this will actually block until the compiler is finished
  243. auto err = data.get();
  244. ```
  245. [endsect]
  246. [section:group Groups]
  247. When launching several processes, processes can be grouped together.
  248. This will also apply for a child process, that launches other processes,
  249. if they do not modify the group membership. E.g. if you call `make` which
  250. launches other processes and call terminate on it,
  251. it will not terminate all the child processes of the child unless you use a group.
  252. The two main reasons to use groups are:
  253. # Being able to terminate child processes of the child process
  254. # Grouping several processes into one, just so they can be terminated at once
  255. If we have program like `make`, which does launch its own child processes,
  256. a call of child_terminate might not suffice. I.e. if we have a makefile launching `gcc`
  257. and use the following code, the `gcc` process will still run afterwards:
  258. ```
  259. bp::child c("make");
  260. if (!c.child_wait_for(std::chrono::seconds(10)) //give it 10 seconds
  261. c.child_terminate(); //then terminate
  262. ```
  263. So in order to also terminate `gcc` we can use a group.
  264. ```
  265. bp::group g;
  266. bp::child c("make", g);
  267. if (!g.group_wait_for(std::chrono::seconds(10))
  268. g.group_terminate();
  269. c.child_wait(); //to avoid a zombie process & get the exit code
  270. ```
  271. Now given the example, we still call child_wait to avoid a zombie process.
  272. An easier solution for that might be to use [funcref boost::process::spawn spawn].
  273. To put two processes into one group, the following code suffices. Spawn already
  274. launches a detached process (i.e. without a child-handle), but they can be grouped,
  275. to that in the case of a problem, RAII is still a given.
  276. ```
  277. void f()
  278. {
  279. bp::group g;
  280. bp::spawn("foo", g);
  281. bp::spawn("bar", g);
  282. do_something();
  283. g.group_wait();
  284. };
  285. ```
  286. In the example, it will wait for both processes at the end of the function unless
  287. an exception occurs. I.e. if an exception is thrown, the group will be terminated.
  288. Please see the [headerref boost/process/group.hpp reference] for more information.
  289. [endsect]
  290. [section:env Environment]
  291. This library provides access to the environment of the current process and allows
  292. setting it for the child process.
  293. ```
  294. //get a handle to the current environment
  295. auto env = boost::this_process::environment();
  296. //add a variable to the current environment
  297. env["VALUE_1"] = "foo";
  298. //copy it into an environment separate to the one of this process
  299. bp::environment env_ = env;
  300. //append two values to a variable in the new env
  301. env_["VALUE_2"] += {"bar1", "bar2"};
  302. //launch a process with `env_`
  303. bp::system("stuff", env_);
  304. ```
  305. A more convenient way to modify the environment for the child is the
  306. [globalref boost::process::env env] property, which the example as following:
  307. ```
  308. bp::system("stuff", bp::env["VALUE_1"]="foo", bp::env["VALUE_2"]+={"bar1", "bar2"});
  309. ```
  310. Please see to the [headerref boost/process/environment.hpp reference] for more information.
  311. [endsect]
  312. [endsect]