Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

child.hpp 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. // \file child.hpp
  2. //
  3. // Copyright (C) 2014 MicroNeil Research Corporation.
  4. //
  5. // This program is part of the MicroNeil Research Open Library Project. For
  6. // more information go to http://www.microneil.com/OpenLibrary/index.html
  7. //
  8. // This program is free software; you can redistribute it and/or modify it
  9. // under the terms of the GNU General Public License as published by the
  10. // Free Software Foundation; either version 2 of the License, or (at your
  11. // option) any later version.
  12. //
  13. // This program is distributed in the hope that it will be useful, but WITHOUT
  14. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  16. // more details.
  17. //
  18. // You should have received a copy of the GNU General Public License along with
  19. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  20. // Place, Suite 330, Boston, MA 02111-1307 USA
  21. //==============================================================================
  22. /*
  23. \brief The child module provides classes to spawn and communicate
  24. with child processes.
  25. */
  26. #ifndef CHILD_HPP
  27. #define CHILD_HPP
  28. #ifdef _WIN32
  29. #include <windows.h>
  30. #endif
  31. #include <cstdint>
  32. #include <streambuf>
  33. #include <iostream>
  34. #include <string>
  35. #include <vector>
  36. #include <thread>
  37. #include <mutex>
  38. namespace CodeDweller {
  39. /**
  40. \namespace CodeDweller
  41. The CodeDweller namespace contains components providing high-level
  42. functionality for applications.
  43. */
  44. /** Class that abstracts the iostreams communication with a child
  45. process.
  46. This class provides functionality to create a child process,
  47. communicate with the child process via streams and signals, and
  48. obtain the exit code of the child process.
  49. */
  50. class ChildStream : public std::iostream {
  51. private:
  52. /// Streambuf class for reading from the standard output and
  53. /// writing to the standard input of the child process.
  54. class ChildStreambuf : public std::streambuf {
  55. friend class ChildStream;
  56. public:
  57. /// Constructor.
  58. //
  59. // \param[in] bufSize is the size in bytes of the input
  60. // buffer and output buffer.
  61. //
  62. explicit ChildStreambuf(std::size_t bufSize = 4096);
  63. #ifdef _WIN32
  64. /// Set the handle to read the standard output of the child
  65. /// process.
  66. //
  67. // \param[in] inHandle is the input handle for the standard
  68. // output of the child process.
  69. //
  70. void setInputHandle(HANDLE inHandle);
  71. /// Set the handle to write the standard input of the child
  72. /// process.
  73. //
  74. // \param[in] outHandle is the output handle for the standard
  75. // input of the child process.
  76. //
  77. void setOutputHandle(HANDLE outHandle);
  78. #else
  79. /// Set the file descriptor to read the standard output of the
  80. /// child process.
  81. //
  82. // \param[in] inFd is the input file descriptor for the standard
  83. // output of the child process.
  84. //
  85. void setInputFileDescriptor(int inFd);
  86. /// Set the file descriptor to write the standard input of the
  87. /// child process.
  88. //
  89. // \param[in] outFd is the output file descriptor for the
  90. // standard input of the child process.
  91. //
  92. void setOutputFileDescriptor(int outFd);
  93. #endif
  94. private:
  95. /** Return the number of bytes that can be read without
  96. blocking.
  97. This method checks if any input is available from the pipe,
  98. and returns the number of bytes in the input buffer plus 1.
  99. Reading that number of bytes will not block. Reading a
  100. larger number of bytes might block.
  101. \returns minimum number of bytes that can be read without
  102. blocking.
  103. */
  104. size_t numBytesAvailable() const;
  105. /// Override streambuf::underflow().
  106. int_type underflow();
  107. /// Flush the output buffer.
  108. void flushBuffer();
  109. /// Override streambuf::overflow().
  110. int_type overflow(int_type ch);
  111. /// Override streambuf::sync().
  112. int sync();
  113. /// Input and output handles.
  114. #ifdef _WIN32
  115. HANDLE inputHandle;
  116. HANDLE outputHandle;
  117. #else
  118. int inputFileDescriptor;
  119. int outputFileDescriptor;
  120. #endif
  121. /// Size of buffers.
  122. std::size_t bufferSize;
  123. /// Read buffer.
  124. std::vector<char> readBuffer;
  125. /// Write buffer.
  126. std::vector<char> writeBuffer;
  127. /// Copy constructor not implemented.
  128. ChildStreambuf(const ChildStreambuf &) = delete;
  129. /// Assignment operator not implemented.
  130. ChildStreambuf &operator=(const ChildStreambuf &) = delete;
  131. };
  132. /// Stream buffer for reading from the stdout and writing to the
  133. /// stdin of the child process.
  134. ChildStreambuf childStreambuf;
  135. public:
  136. /** Constructor for spawning with command-line parameters.
  137. The constructor configures the object, and spawns the child
  138. process.
  139. \param[in] args contains the child executable file name and
  140. command-line parameters. args[0] contains the full path of the
  141. executable, and args[1] thru args[n] are the command-line
  142. parameters.
  143. \param[in] bufSize is the input and output buffer size of the
  144. stream used to communicate with the child process.
  145. \throws runtime_error if an error occurs.
  146. */
  147. ChildStream(std::vector<std::string> const &args, size_t bufSize = 4096);
  148. /** Constructor for spawning without command-line parameters.
  149. The constructor configures the object, and spawns the child
  150. process.
  151. \param[in] childpath contains the child executable file name.
  152. \param[in] bufSize is the input and output buffer size of the
  153. stream used to communicate with the child process.
  154. \throws runtime_error if an error occurs.
  155. */
  156. ChildStream(std::string const &childpath, size_t bufSize = 4096);
  157. /** Constructor.
  158. The constructor configures the I/O buffers, but doesn't spawn
  159. any child process.
  160. \param[in] bufSize is the input and output buffer size of the
  161. stream used to communicate with the child process.
  162. */
  163. ChildStream(size_t bufSize = 4096);
  164. /** Destructor terminates the child process. */
  165. ~ChildStream();
  166. /** Spawn the child process.
  167. \param[in] args contains the child executable file name and
  168. command-line parameters. args[0] contains the full path of the
  169. executable, and args[1] thru args[n] are the command-line
  170. parameters.
  171. \throws runtime_error if an error occurs.
  172. \throws runtime_error if an error occurs.
  173. */
  174. void open(std::vector<std::string> const &args);
  175. /** Spawn the child process.
  176. \param[in] childpath contains the child executable file name.
  177. \throws runtime_error if an error occurs.
  178. */
  179. void open(std::string const &childpath);
  180. /** Get the number of bytes available for input.
  181. @returns number of bytes that can be read without blocking.
  182. */
  183. size_t numBytesAvailable() const;
  184. /** Check whether the child process is running.
  185. \returns True if the child process is running, false
  186. otherwise.
  187. */
  188. bool isRunning() const;
  189. /** Terminate the child process.
  190. \throws runtime_error if an error occurs.
  191. \throws logic_error if the child process is not running.
  192. */
  193. void close();
  194. /** Check whether the child process has exited.
  195. \returns True if the child process has exited, false
  196. otherwise.
  197. \throws runtime_error if an error occurs.
  198. \throws logic_error if the child process is not running.
  199. */
  200. bool isDone();
  201. /** Get the exit value of the child process.
  202. \returns The exit value of the child process if the child
  203. process has exited.
  204. \throws runtime_error if an error occurs.
  205. \throws logic_error if the child process has not exited.
  206. \throws logic_error if the child process is not running.
  207. */
  208. int32_t result();
  209. private:
  210. /** Spawn the child process.
  211. \throws runtime_error if an error occurs.
  212. */
  213. void run();
  214. /// Exit code to use when terminating the child process.
  215. static const uint32_t terminateExitCode = 0;
  216. /// True if the child process was successfully started.
  217. bool childStarted;
  218. /// True if the child process has exited.
  219. bool childExited;
  220. /// Initialize data members.
  221. void init();
  222. /// Child executable path and command-line parameters.
  223. std::vector<std::string> cmdArgs;
  224. #ifdef _WIN32
  225. /// Child's process handle.
  226. HANDLE childProcess;
  227. /// Child's thread handle.
  228. HANDLE childThread;
  229. #else
  230. /// Child process ID.
  231. pid_t childPid;
  232. #endif
  233. /// Exit value of the process.
  234. int32_t exitCode;
  235. /// True if the exit code has been obtained.
  236. bool exitCodeObtainedFlag;
  237. /// Return text for the most recent error.
  238. //
  239. // \returns Human-readable description of the most recent error.
  240. //
  241. static std::string getErrorText();
  242. };
  243. /** Class that abstracts the non-blocking communication with a child
  244. process.
  245. This class provides functionality to create a child process,
  246. communicate with the child process via non-blocking methods, and
  247. obtain the exit code of the child process.
  248. */
  249. class Child {
  250. private:
  251. /** Circular buffer of characters. */
  252. class CircularBuffer {
  253. public:
  254. /** Constructor specifies the capacity.
  255. @param[in] maxSize is the capacity of the buffer.
  256. */
  257. CircularBuffer(size_t maxSize);
  258. /** Check whether the container is empty.
  259. @returns true if the container is empty, false otherwise.
  260. */
  261. bool empty() const;
  262. /** Get the size.
  263. @returns the number of bytes in the buffer.
  264. */
  265. size_t nUsed() const;
  266. /** Get the available space.
  267. @returns the number of bytes that can be written to the
  268. buffer without overwriting any existing data.
  269. */
  270. size_t nFree() const;
  271. /** Clear the buffer. */
  272. void clear();
  273. /** Put bytes to the buffer.
  274. @param[in] ptr is the address of the first byte to put.
  275. @param[in] nBytes is the number of bytes to put.
  276. */
  277. void put(char const *ptr, size_t nBytes);
  278. /** Get bytes from the buffer.
  279. This method gets the specified number of bytes from the
  280. buffer, and erases those bytes from the buffer.
  281. @param[out] buf receives the data. The contents of buf are
  282. replaced with the data in the circular buffer.
  283. @param[in] nBytes is the number of bytes to get. Specifying
  284. a value of zero for nBytes gets and erases all the data.
  285. */
  286. void getAndErase(std::string &buf, size_t nBytes = 0);
  287. private:
  288. /** Increment the index.
  289. @param[in] index is the index to increment.
  290. */
  291. void nextIndex(size_t &index) const {
  292. index++;
  293. if (index >= capacity)
  294. index = 0;
  295. }
  296. /// Buffer to hold data.
  297. std::vector<char> buffer;
  298. /// Capacity of the buffer.
  299. size_t capacity;
  300. /// Index of first element.
  301. size_t iBegin;
  302. /// Index of one past the last element.
  303. size_t iEnd;
  304. };
  305. public:
  306. /** Constructor for spawning with command-line parameters.
  307. The constructor configures the object, and spawns the child
  308. process.
  309. \param[in] args contains the child executable file name and
  310. command-line parameters. args[0] contains the full path of the
  311. executable, and args[1] thru args[n] are the command-line
  312. parameters.
  313. \param[in] bufSize is the input and output buffer size of the
  314. stream used to communicate with the child process.
  315. \param[in] nominalAboveMinPollTime_ms is used to determine the
  316. minimum time in milliseconds that the writer thread sleeps
  317. when there's no data in the output buffer, and that the reader
  318. thread sleeps when there's no room in the input buffer. The
  319. minimum time is nominalAboveMinPollTime_ms +
  320. CodeDweller::MinimumSleeperTime.
  321. \param[in] deltaPollTime_ms is how much longer, in
  322. milliseconds, the maximum time to sleep is than the minimum time.
  323. \throws runtime_error if an error occurs.
  324. */
  325. Child(std::vector<std::string> const &args,
  326. size_t bufSize = 128 * 1024,
  327. std::uint16_t nominalAboveMinPollTime_ms = 0,
  328. std::uint16_t deltaPollTime_ms = 500);
  329. /** Constructor for spawning without command-line parameters.
  330. The constructor configures the object, and spawns the child
  331. process.
  332. \param[in] childpath contains the child executable file name.
  333. \param[in] bufSize is the input and output buffer size of the
  334. stream used to communicate with the child process.
  335. \param[in] nominalAboveMinPollTime_ms is used to determine the
  336. minimum time in milliseconds that the writer thread sleeps
  337. when there's no data in the output buffer, and that the reader
  338. thread sleeps when there's no room in the input buffer. The
  339. minimum time is nominalAboveMinPollTime_ms +
  340. CodeDweller::MinimumSleeperTime.
  341. \param[in] deltaPollTime_ms is how much longer, in
  342. milliseconds, the maximum time to sleep is than the minimum time.
  343. \throws runtime_error if an error occurs.
  344. */
  345. Child(std::string const &childpath,
  346. size_t bufSize = 128 * 1024,
  347. std::uint16_t nominalAboveMinPollTime_ms = 0,
  348. std::uint16_t deltaPollTime_ms = 500);
  349. /** Constructor.
  350. The constructor configures the I/O buffers, but doesn't spawn
  351. any child process.
  352. \param[in] bufSize is the input and output buffer size of the
  353. stream used to communicate with the child process.
  354. \param[in] nominalAboveMinPollTime_ms is used to determine the
  355. minimum time in milliseconds that the writer thread sleeps
  356. when there's no data in the output buffer, and that the reader
  357. thread sleeps when there's no room in the input buffer. The
  358. minimum time is nominalAboveMinPollTime_ms +
  359. CodeDweller::MinimumSleeperTime.
  360. \param[in] deltaPollTime_ms is how much longer, in
  361. milliseconds, the maximum time to sleep is than the minimum time.
  362. */
  363. Child(size_t bufSize = 4096,
  364. std::uint16_t nominalAboveMinPollTime_ms = 0,
  365. std::uint16_t deltaPollTime_ms = 500);
  366. /** Destructor terminates the child process. */
  367. ~Child();
  368. /** Spawn the child process.
  369. \param[in] args contains the child executable file name and
  370. command-line parameters. args[0] contains the full path of the
  371. executable, and args[1] thru args[n] are the command-line
  372. parameters.
  373. \throws runtime_error if an error occurs.
  374. \throws runtime_error if an error occurs.
  375. */
  376. void open(std::vector<std::string> const &args);
  377. /** Spawn the child process.
  378. \param[in] childpath contains the child executable file name.
  379. \throws runtime_error if an error occurs.
  380. */
  381. void open(std::string const &childpath);
  382. /** All-or-nothing non-blocking queue write request to the child.
  383. This methods attempts to queue a write request consisting of
  384. the entire contents of the string.
  385. @param[in] data is the data to queue.
  386. @returns true if the write request was queued, false
  387. otherwise.
  388. */
  389. bool write(std::string const &data);
  390. /** Non-blocking queue write request to the child.
  391. This methods attempts to queue a write request consisting of
  392. as much as possible of the contents of the string.
  393. @param[in, out] data on input is the data to queue. On
  394. output, data contains the data that was not queued.
  395. @returns the number of bytes queued.
  396. */
  397. size_t writeAndShrink(std::string &data);
  398. /** Check if all queued data was transmitted.
  399. @returns true if all the queued data was transmitted to the
  400. child, false otherwise.
  401. */
  402. bool isFinishedWriting() const;
  403. /** Non-blocking request to get data read from the child.
  404. This method attempts to get up to a specified number of bytes
  405. of data from the input buffer containing data received from
  406. the child. The data that is provided is erased from the input
  407. buffer.
  408. @param[out] data contains the copied data.
  409. @param[in] nBytes is the number of bytes to attempt to copy.
  410. If nBytes is zero, the contents of the entire input buffer is
  411. moved to data.
  412. @returns the number of bytes copied.
  413. */
  414. size_t read(std::string &data, size_t nBytes = 0);
  415. /** Check whether the child process is running.
  416. \returns True if the child process is running, false
  417. otherwise.
  418. */
  419. bool isRunning() const;
  420. /** Check error status.
  421. This method checks whether an error occurred when
  422. communicating with the child process.
  423. \param[out] errorDescription contains any description of the
  424. error.
  425. \returns true if an error occurred, false otherwise.
  426. */
  427. bool errorOccurred(std::string &errorDescription) const;
  428. /** Close the connection.
  429. This method terminate the child process if it is running, and
  430. resets the object. After this method is invoked, open() can
  431. be invoked to spawn and communicate with another child
  432. process.
  433. \throws runtime_error if an error occurs.
  434. \throws logic_error if the child process is not running.
  435. */
  436. void close();
  437. /** Check whether the child process has exited.
  438. \returns True if the child process has exited, false
  439. otherwise.
  440. \throws runtime_error if an error occurs.
  441. \throws logic_error if the child process is not running.
  442. */
  443. bool isDone();
  444. /** Get the exit value of the child process.
  445. \returns The exit value of the child process if the child
  446. process has exited.
  447. \throws runtime_error if an error occurs.
  448. \throws logic_error if the child process has not exited.
  449. \throws logic_error if the child process is not running.
  450. */
  451. int32_t result();
  452. private:
  453. /// Initialize data members.
  454. void init();
  455. /** Spawn the child process.
  456. \throws runtime_error if an error occurs.
  457. */
  458. void run();
  459. /// Reader thread object.
  460. std::thread readerThread;
  461. /// Thread start function to read data from the child.
  462. void readFromChild();
  463. /// Writer thread object.
  464. std::thread writerThread;
  465. /// Thread start function to send data to the child.
  466. void writeToChild();
  467. /// True if readerThread and writerThread are to stop.
  468. bool stopFlag;
  469. /// True if both the reader and writer the writer threads are
  470. /// running, false otherwise.
  471. bool threadsAreRunning;
  472. /// Description of any error.
  473. std::string errorText;
  474. /// Input and output handles.
  475. #ifdef _WIN32
  476. HANDLE inputHandle;
  477. HANDLE outputHandle;
  478. #else
  479. int inputFileDescriptor;
  480. int outputFileDescriptor;
  481. #endif
  482. /// Capacity of buffers.
  483. std::size_t bufferCapacity;
  484. /// Read buffer.
  485. CircularBuffer readBuffer;
  486. /// Mutex to serialize access to readBuffer.
  487. std::mutex readBufferMutex;
  488. /// Write buffer.
  489. std::vector<char> writeBuffer;
  490. /// Number of bytes in writeBuffer.
  491. size_t nWriteBytes;
  492. /// Mutex to serialize access to writeBuffer.
  493. std::mutex writeBufferMutex;
  494. /// Number of bytes in writer thread transmit buffer.
  495. size_t nTransmitBytes;
  496. /// Nominal poll time.
  497. //
  498. // If there isn't room in readBuffer, readerThread aperiodically
  499. // checks whether room is available. The check times are
  500. // determined by a CodeDweller::PollTimer object, which requires a
  501. // nominal poll time and a maximum poll time.
  502. int nominalPollTime_ms;
  503. /// Maximum poll time.
  504. int maximumPollTime_ms;
  505. /// Exit code to use when terminating the child process.
  506. static const uint32_t terminateExitCode = 0;
  507. /// True if the child process was successfully started.
  508. bool childStarted;
  509. /// True if the child process has exited.
  510. bool childExited;
  511. /// Child executable path and command-line parameters.
  512. std::vector<std::string> cmdArgs;
  513. #ifdef _WIN32
  514. /// Child's process handle.
  515. HANDLE childProcess;
  516. /// Child's thread handle.
  517. HANDLE childThread;
  518. #else
  519. /// Child process ID.
  520. pid_t childPid;
  521. #endif
  522. /// Exit value of the process.
  523. int32_t exitCode;
  524. /// True if the exit code has been obtained.
  525. bool exitCodeObtainedFlag;
  526. /// Return text for the most recent error.
  527. //
  528. // \returns Human-readable description of the most recent error.
  529. //
  530. static std::string getErrorText();
  531. };
  532. }
  533. #endif // CHILD_HPP