You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

child.cpp 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  1. // \file child.cpp
  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. #ifndef _WIN32
  23. #include <unistd.h>
  24. #include <sys/types.h>
  25. #include <sys/wait.h>
  26. #include <signal.h>
  27. #include <sys/select.h>
  28. #include <cstring>
  29. #include <cerrno>
  30. /// Dummy used to suppressed warnings about unused values.
  31. int iDummy;
  32. #endif
  33. #include <stdexcept>
  34. #include <utility>
  35. #include "CodeDweller/timing.hpp"
  36. #include "CodeDweller/child.hpp"
  37. namespace CodeDweller {
  38. ChildStream::ChildStream(std::vector<std::string> const &args,
  39. size_t bufSize) :
  40. std::iostream(&childStreambuf),
  41. childStreambuf(bufSize),
  42. cmdArgs(args) {
  43. init();
  44. run();
  45. }
  46. ChildStream::ChildStream(std::string const &childpath, size_t bufSize) :
  47. std::iostream(&childStreambuf),
  48. childStreambuf(bufSize) {
  49. cmdArgs.push_back(childpath);
  50. init();
  51. run();
  52. }
  53. ChildStream::ChildStream(size_t bufSize) :
  54. std::iostream(&childStreambuf),
  55. childStreambuf(bufSize) {
  56. init();
  57. }
  58. ChildStream::~ChildStream() {
  59. try {
  60. close();
  61. } catch (std::exception &e) {
  62. ;
  63. }
  64. }
  65. void ChildStream::init() {
  66. childStarted = false;
  67. childExited = false;
  68. exitCodeObtainedFlag = false;
  69. exitCode = 0;
  70. }
  71. void ChildStream::open(std::vector<std::string> const &args) {
  72. cmdArgs = args;
  73. init();
  74. run();
  75. }
  76. void ChildStream::open(std::string const &childpath) {
  77. cmdArgs.clear();
  78. cmdArgs.push_back(childpath);
  79. init();
  80. run();
  81. }
  82. size_t ChildStream::numBytesAvailable() const {
  83. return childStreambuf.numBytesAvailable();
  84. }
  85. bool ChildStream::isRunning() const {
  86. return childStarted && !childExited;
  87. }
  88. void ChildStream::run() {
  89. if (childStarted) {
  90. throw std::logic_error("Child process was active when "
  91. "run() was called");
  92. }
  93. if (cmdArgs.empty()) {
  94. throw std::invalid_argument("A child executable must be specified.");
  95. }
  96. #ifdef _WIN32
  97. // Set the bInheritHandle flag so pipe handles are inherited.
  98. SECURITY_ATTRIBUTES securityAttributes;
  99. securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
  100. securityAttributes.bInheritHandle = true;
  101. securityAttributes.lpSecurityDescriptor = NULL;
  102. // Create a pipe for the child process's STDOUT.
  103. HANDLE childStdOutAtChild;
  104. HANDLE childStdOutAtParent;
  105. HANDLE childStdInAtChild;
  106. HANDLE childStdInAtParent;
  107. int bufferSize = 0;
  108. if (!CreatePipe(&childStdOutAtParent,
  109. &childStdOutAtChild,
  110. &securityAttributes,
  111. bufferSize)) {
  112. throw std::runtime_error("Error from CreatePipe for stdout: " +
  113. getErrorText());
  114. }
  115. // Ensure the read handle to the pipe for STDOUT is not inherited.
  116. int inheritFlag = 0;
  117. if (!SetHandleInformation(childStdOutAtParent,
  118. HANDLE_FLAG_INHERIT,
  119. inheritFlag) ) {
  120. throw std::runtime_error("Error from GetHandleInformation for stdout: " +
  121. getErrorText());
  122. }
  123. // Create a pipe for the child process's STDIN.
  124. if (! CreatePipe(&childStdInAtChild,
  125. &childStdInAtParent,
  126. &securityAttributes,
  127. bufferSize)) {
  128. throw std::runtime_error("Error from CreatePipe for stdin: " +
  129. getErrorText());
  130. }
  131. // Ensure the write handle to the pipe for STDIN is not inherited.
  132. if (!SetHandleInformation(childStdInAtParent,
  133. HANDLE_FLAG_INHERIT,
  134. inheritFlag)) {
  135. throw std::runtime_error("Error from GetHandleInformation for stdin: " +
  136. getErrorText());
  137. }
  138. // Set up members of the PROCESS_INFORMATION structure.
  139. PROCESS_INFORMATION processInfo;
  140. std::fill((char *) &processInfo,
  141. ((char *) &processInfo) + sizeof(PROCESS_INFORMATION),
  142. 0);
  143. // Set up members of the STARTUPINFO structure. This structure
  144. // specifies the STDIN and STDOUT handles for redirection.
  145. STARTUPINFO startInfo;
  146. std::fill((char *) &startInfo,
  147. ((char *) &startInfo) + sizeof(STARTUPINFO),
  148. 0);
  149. startInfo.cb = sizeof(STARTUPINFO);
  150. startInfo.hStdError = childStdOutAtChild;
  151. startInfo.hStdOutput = childStdOutAtChild;
  152. startInfo.hStdInput = childStdInAtChild;
  153. startInfo.dwFlags |= STARTF_USESTDHANDLES;
  154. // Assemble the command line.
  155. std::string cmdline;
  156. if (cmdArgs.size() == 1) {
  157. cmdline = cmdArgs[0];
  158. } else {
  159. // Append all but last command-line arguments.
  160. for (size_t i = 0; i < cmdArgs.size() - 1; i++) {
  161. cmdline += cmdArgs[i] + " ";
  162. }
  163. cmdline += cmdArgs.back(); // Append last command-line argument.
  164. }
  165. // Create the child process.
  166. bool status;
  167. status = CreateProcess(NULL,
  168. (char *) cmdline.c_str(),
  169. NULL, // process security attributes
  170. NULL, // primary thread security attributes
  171. true, // handles are inherited
  172. 0, // creation flags
  173. NULL, // use parent's environment
  174. NULL, // use parent's current directory
  175. &startInfo, // STARTUPINFO pointer
  176. &processInfo); // receives PROCESS_INFORMATION
  177. // If an error occurs, exit the application.
  178. if (!status ) {
  179. throw std::runtime_error("Error from CreateProcess with "
  180. "command line \"" + cmdline + "\": " +
  181. getErrorText());
  182. }
  183. // Provide the stream buffers with the handles for communicating
  184. // with the child process.
  185. childStreambuf.setInputHandle(childStdOutAtParent);
  186. childStreambuf.setOutputHandle(childStdInAtParent);
  187. // Save the handles to the child process and its primary thread.
  188. childProcess = processInfo.hProcess;
  189. childThread = processInfo.hThread;
  190. // Close the child's end of the pipes.
  191. if (!CloseHandle(childStdOutAtChild)) {
  192. throw std::runtime_error("Error closing the child process "
  193. "stdout handle: " + getErrorText());
  194. }
  195. if (!CloseHandle(childStdInAtChild)) {
  196. throw std::runtime_error("Error closing the child process "
  197. "stdin handle: " + getErrorText());
  198. }
  199. #else
  200. // Create the pipes for the stdin and stdout.
  201. int childStdInPipe[2];
  202. int childStdOutPipe[2];
  203. if (pipe(childStdInPipe) != 0) {
  204. throw std::runtime_error("Error creating pipe for stdin: " +
  205. getErrorText());
  206. }
  207. if (pipe(childStdOutPipe) != 0) {
  208. ::close(childStdInPipe[0]);
  209. ::close(childStdInPipe[1]);
  210. throw std::runtime_error("Error creating pipe for stdout: " +
  211. getErrorText());
  212. }
  213. // Create the child process.
  214. childPid = fork();
  215. if (-1 == childPid) {
  216. for (int i = 0; i < 2; i++) {
  217. ::close(childStdInPipe[i]);
  218. ::close(childStdOutPipe[i]);
  219. }
  220. throw std::runtime_error("Error creating child process: " +
  221. getErrorText());
  222. }
  223. if (0 == childPid) {
  224. // The child executes this. Redirect stdin.
  225. if (dup2(childStdInPipe[0], STDIN_FILENO) == -1) {
  226. std::string errMsg;
  227. // Send message to parent.
  228. errMsg = "Error redirecting stdin in the child: " + getErrorText();
  229. iDummy = ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  230. exit(-1);
  231. }
  232. // Redirect stdout.
  233. if (dup2(childStdOutPipe[1], STDOUT_FILENO) == -1) {
  234. std::string errMsg;
  235. // Send message to parent.
  236. errMsg = "Error redirecting stdout in the child: " + getErrorText();
  237. iDummy = ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  238. exit(-1);
  239. }
  240. // Close pipes.
  241. if ( (::close(childStdInPipe[0]) != 0) ||
  242. (::close(childStdInPipe[1]) != 0) ||
  243. (::close(childStdOutPipe[0]) != 0) ||
  244. (::close(childStdOutPipe[1]) != 0) ) {
  245. std::string errMsg;
  246. // Send message to parent.
  247. errMsg = "Error closing the pipes in the child: " + getErrorText();
  248. iDummy = ::write(STDOUT_FILENO, errMsg.data(), errMsg.size());
  249. exit(-1);
  250. }
  251. // Prepare the arguments.
  252. std::vector<const char *> execvArgv;
  253. for (auto &arg : cmdArgs) {
  254. execvArgv.push_back(arg.c_str());
  255. }
  256. execvArgv.push_back((char *) NULL);
  257. // Run the child process image.
  258. (void) execv(execvArgv[0], (char * const *) &(execvArgv[0]));
  259. // Error from exec.
  260. std::string errMsg;
  261. // Send message to parent.
  262. errMsg = "Error from exec: " + getErrorText();
  263. iDummy = ::write(STDOUT_FILENO, errMsg.data(), errMsg.size());
  264. exit(-1);
  265. }
  266. // Provide the stream buffers with the file descriptors for
  267. // communicating with the child process.
  268. childStreambuf.setInputFileDescriptor(childStdOutPipe[0]);
  269. childStreambuf.setOutputFileDescriptor(childStdInPipe[1]);
  270. // Close the child's end of the pipes.
  271. if ( (::close(childStdInPipe[0]) != 0) ||
  272. (::close(childStdOutPipe[1]) != 0) ) {
  273. std::string errMsg;
  274. throw std::runtime_error("Error closing child's end of pipes in "
  275. "the parent: " + getErrorText());
  276. }
  277. #endif
  278. childStarted = true;
  279. }
  280. void ChildStream::close() {
  281. if (!childStarted) {
  282. throw std::logic_error("Child process was not started "
  283. "when close() was called");
  284. }
  285. // Terminate the child if it's running.
  286. if (isRunning()) {
  287. std::string errorString;
  288. bool errorOccurred = false;
  289. #ifdef _WIN32
  290. // Ignore errors. Reason: Terminating a proces that doesn't
  291. // exist (e.g. has exited) gives an error.
  292. (void) TerminateProcess(childProcess, terminateExitCode);
  293. #else
  294. if (kill(childPid, SIGKILL) != 0) {
  295. errorString += (errorOccurred ? "\n" : "");
  296. errorString += "Error terminating the child process: " +
  297. getErrorText();
  298. errorOccurred = true;
  299. } else if (waitpid(childPid, NULL, 0) != childPid) {
  300. errorString += (errorOccurred ? "\n" : "");
  301. errorString += "Error waiting for the child process: " +
  302. getErrorText();
  303. errorOccurred = true;
  304. }
  305. #endif
  306. if (errorOccurred) {
  307. throw std::runtime_error(errorString);
  308. }
  309. }
  310. // Reset.
  311. init();
  312. }
  313. bool ChildStream::isDone() {
  314. if (childExited) {
  315. return true;
  316. }
  317. if (!childStarted) {
  318. throw std::logic_error("Child process was not started "
  319. "when isDone() was called");
  320. }
  321. int result;
  322. #ifdef _WIN32
  323. if (!GetExitCodeProcess(childProcess, (LPDWORD) &result)) {
  324. throw std::runtime_error("Error checking status of child process: " +
  325. getErrorText());
  326. }
  327. if (STILL_ACTIVE == result) {
  328. return false;
  329. }
  330. // Child process has exited. Save the exit code.
  331. exitCode = result;
  332. exitCodeObtainedFlag = true;
  333. #else
  334. int status = 0;
  335. result = waitpid(childPid, &status, WNOHANG);
  336. if (-1 == result) {
  337. throw std::runtime_error("Error checking status of child process: " +
  338. getErrorText());
  339. } else if (0 == result) {
  340. // Child is still running.
  341. return false;
  342. }
  343. if (WIFEXITED(status)) {
  344. // Child exited normally.
  345. exitCode = WEXITSTATUS(status);
  346. exitCodeObtainedFlag = true;
  347. }
  348. #endif
  349. childExited = true;
  350. return true;
  351. }
  352. int32_t ChildStream::result() {
  353. if (exitCodeObtainedFlag) {
  354. return exitCode;
  355. }
  356. // Check whether the process is running, and get the exit code.
  357. if (!isDone()) {
  358. throw std::logic_error("Child process was still running "
  359. "when result() was called");
  360. }
  361. // Child process has exited.
  362. if (!exitCodeObtainedFlag) {
  363. // Exit code is not available.
  364. throw std::runtime_error("Child process has exited but the exit "
  365. "code is not available");
  366. }
  367. return exitCode;
  368. }
  369. std::string ChildStream::getErrorText() {
  370. #ifdef _WIN32
  371. LPVOID winMsgBuf;
  372. DWORD lastError = GetLastError();
  373. FormatMessage(
  374. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  375. FORMAT_MESSAGE_FROM_SYSTEM |
  376. FORMAT_MESSAGE_IGNORE_INSERTS,
  377. NULL,
  378. lastError,
  379. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  380. (char *) &winMsgBuf,
  381. 0, NULL );
  382. std::string errMsg((char *) winMsgBuf);
  383. LocalFree(winMsgBuf);
  384. return errMsg;
  385. #else
  386. return strerror(errno);
  387. #endif
  388. }
  389. ChildStream::ChildStreambuf::ChildStreambuf(std::size_t bufSize) :
  390. #ifdef _WIN32
  391. inputHandle(0),
  392. outputHandle(0),
  393. #else
  394. inputFileDescriptor(-1),
  395. outputFileDescriptor(-1),
  396. #endif
  397. bufferSize(bufSize),
  398. readBuffer(bufferSize + 1),
  399. writeBuffer(bufferSize + 1) {
  400. // Read buffer initialization.
  401. char *end = &(readBuffer.front()) + readBuffer.size();
  402. // Indicate to underflow that underflow has not been called.
  403. setg(end, end, end);
  404. // Write buffer initialization.
  405. char *base = &(writeBuffer.front());
  406. // Indicate to overflow that overflow has not been called.
  407. setp(base, base + writeBuffer.size() - 1);
  408. }
  409. #ifdef _WIN32
  410. void ChildStream::ChildStreambuf::setInputHandle(HANDLE inHandle) {
  411. inputHandle = inHandle;
  412. }
  413. #else
  414. void ChildStream::ChildStreambuf::setInputFileDescriptor(int inFd) {
  415. inputFileDescriptor = inFd;
  416. }
  417. #endif
  418. size_t ChildStream::ChildStreambuf::numBytesAvailable() const {
  419. size_t nBytesAvailable = egptr() - gptr();
  420. #ifdef _WIN32
  421. DWORD lpTotalBytesAvail;
  422. if (!PeekNamedPipe(inputHandle,
  423. NULL,
  424. 0,
  425. NULL,
  426. &lpTotalBytesAvail,
  427. NULL)) {
  428. throw std::runtime_error("Error from PeekNamedPipe: " +
  429. getErrorText());
  430. }
  431. if (lpTotalBytesAvail > 0) {
  432. nBytesAvailable++;
  433. }
  434. #else
  435. fd_set readFd;
  436. int retVal;
  437. struct timeval timeout = {0, 0};
  438. FD_ZERO(&readFd);
  439. FD_SET(inputFileDescriptor, &readFd);
  440. // Check if input is available.
  441. retVal = select(inputFileDescriptor + 1, &readFd, NULL, NULL, &timeout);
  442. if (-1 == retVal) {
  443. throw std::runtime_error("Error from select(): " + getErrorText());
  444. } else if (retVal > 0) {
  445. nBytesAvailable++;
  446. }
  447. #endif
  448. return nBytesAvailable;
  449. }
  450. std::streambuf::int_type ChildStream::ChildStreambuf::underflow() {
  451. // Check for empty buffer.
  452. if (gptr() < egptr()) {
  453. // Not empty.
  454. return traits_type::to_int_type(*gptr());
  455. }
  456. // Need to fill the buffer.
  457. char *base = &(readBuffer.front());
  458. char *start = base;
  459. // Check whether this is the first fill.
  460. if (eback() == base) {
  461. // Not the first fill. Copy one putback character.
  462. *(eback()) = *(egptr() - 1);
  463. start++;
  464. }
  465. // start points to the start of the buffer. Fill buffer.
  466. #ifdef _WIN32
  467. DWORD nBytesRead;
  468. if (!ReadFile(inputHandle,
  469. start,
  470. readBuffer.size() - (start - base),
  471. &nBytesRead,
  472. NULL)) {
  473. return traits_type::eof();
  474. }
  475. #else
  476. ssize_t nBytesRead;
  477. nBytesRead = ::read(inputFileDescriptor,
  478. start,
  479. readBuffer.size() - (start - base));
  480. if (-1 == nBytesRead) {
  481. return traits_type::eof();
  482. }
  483. #endif
  484. // Check for EOF.
  485. if (0 == nBytesRead) {
  486. return traits_type::eof();
  487. }
  488. // Update buffer pointers.
  489. setg(base, start, start + nBytesRead);
  490. return traits_type::to_int_type(*gptr());
  491. }
  492. #ifdef _WIN32
  493. void ChildStream::ChildStreambuf::setOutputHandle(HANDLE outHandle) {
  494. outputHandle = outHandle;
  495. }
  496. #else
  497. void ChildStream::ChildStreambuf::setOutputFileDescriptor(int outFd) {
  498. outputFileDescriptor = outFd;
  499. }
  500. #endif
  501. void ChildStream::ChildStreambuf::flushBuffer() {
  502. // Write.
  503. std::ptrdiff_t nBytes = pptr() - pbase();
  504. #ifdef _WIN32
  505. DWORD nBytesWritten;
  506. if (!WriteFile(outputHandle,
  507. pbase(),
  508. nBytes,
  509. &nBytesWritten,
  510. NULL)) {
  511. // Clear the output buffer.
  512. pbump(-nBytes);
  513. throw std::runtime_error("Error writing to child process: " +
  514. getErrorText());
  515. }
  516. #else
  517. ssize_t nBytesWritten;
  518. nBytesWritten = ::write(outputFileDescriptor, pbase(), nBytes);
  519. #endif
  520. // Clear the output buffer.
  521. pbump(-nBytes);
  522. if (nBytes != nBytesWritten) {
  523. throw std::runtime_error("Not all data was written to to child "
  524. "process: " + getErrorText());
  525. }
  526. return;
  527. }
  528. std::streambuf::int_type ChildStream::ChildStreambuf::overflow(int_type ch) {
  529. // Check whether we're writing EOF.
  530. if (traits_type::eof() != ch) {
  531. // Not writing EOF.
  532. *(pptr()) = ch;
  533. pbump(1);
  534. // Write.
  535. flushBuffer();
  536. // Success.
  537. return ch;
  538. }
  539. return traits_type::eof();
  540. }
  541. int ChildStream::ChildStreambuf::sync() {
  542. flushBuffer(); // Throws exception on failure.
  543. // Success.
  544. return 1;
  545. }
  546. Child::CircularBuffer::CircularBuffer(size_t maxSize) :
  547. buffer(maxSize + 1),
  548. capacity(maxSize) {
  549. iBegin = 0;
  550. iEnd = 0;
  551. }
  552. bool Child::CircularBuffer::empty() const {
  553. return (iBegin == iEnd);
  554. }
  555. size_t Child::CircularBuffer::nUsed() const {
  556. return capacity - nFree();
  557. }
  558. void Child::CircularBuffer::clear() {
  559. iBegin = 0;
  560. iEnd = 0;
  561. }
  562. size_t Child::CircularBuffer::nFree() const {
  563. size_t iLocalBegin = iBegin;
  564. // Correct an invalid value.
  565. if (iLocalBegin >= capacity + 1) {
  566. iLocalBegin = 0;
  567. }
  568. if (iLocalBegin <= iEnd) {
  569. return capacity - (iEnd - iLocalBegin);
  570. }
  571. return iLocalBegin - iEnd - 1;
  572. }
  573. void Child::CircularBuffer::put(char const *ptr, size_t nBytes) {
  574. for (size_t i = 0; i < nBytes; i++) {
  575. buffer[iEnd] = *ptr;
  576. ptr++;
  577. nextIndex(iEnd);
  578. }
  579. }
  580. Child::Child(std::vector<std::string> const &args,
  581. size_t bufSize,
  582. std::uint16_t nominalAboveMinPollTime_ms,
  583. std::uint16_t deltaPollTime_ms) :
  584. bufferCapacity(bufSize),
  585. readBuffer(bufferCapacity),
  586. writeBuffer(bufferCapacity),
  587. nominalPollTime_ms(nominalAboveMinPollTime_ms +
  588. CodeDweller::MinimumSleeperTime),
  589. maximumPollTime_ms(nominalPollTime_ms + deltaPollTime_ms) {
  590. init();
  591. open(args);
  592. }
  593. Child::Child(std::string const &childpath,
  594. size_t bufSize,
  595. std::uint16_t nominalAboveMinPollTime_ms,
  596. std::uint16_t deltaPollTime_ms) :
  597. bufferCapacity(bufSize),
  598. readBuffer(bufferCapacity),
  599. writeBuffer(bufferCapacity),
  600. nominalPollTime_ms(nominalAboveMinPollTime_ms +
  601. CodeDweller::MinimumSleeperTime),
  602. maximumPollTime_ms(nominalPollTime_ms + deltaPollTime_ms) {
  603. init();
  604. open(childpath);
  605. }
  606. Child::Child(size_t bufSize,
  607. std::uint16_t nominalAboveMinPollTime_ms,
  608. std::uint16_t deltaPollTime_ms) :
  609. bufferCapacity(bufSize),
  610. readBuffer(bufferCapacity),
  611. writeBuffer(bufferCapacity),
  612. nominalPollTime_ms(nominalAboveMinPollTime_ms +
  613. CodeDweller::MinimumSleeperTime),
  614. maximumPollTime_ms(nominalPollTime_ms + deltaPollTime_ms) {
  615. init();
  616. }
  617. Child::~Child() {
  618. try {
  619. close();
  620. } catch (std::exception &e) {
  621. ;
  622. }
  623. }
  624. void Child::open(std::vector<std::string> const &args) {
  625. cmdArgs = args;
  626. if (isRunning()) {
  627. throw std::logic_error("The child process was already active.");
  628. }
  629. init();
  630. run();
  631. }
  632. void Child::open(std::string const &childpath) {
  633. if (isRunning()) {
  634. throw std::logic_error("The child process was already active.");
  635. }
  636. cmdArgs.clear();
  637. cmdArgs.push_back(childpath);
  638. init();
  639. run();
  640. }
  641. void Child::init() {
  642. childStarted = false;
  643. childExited = false;
  644. childExitedInferred = false;
  645. exitCodeObtainedFlag = false;
  646. exitCode = 0;
  647. readBuffer.clear();
  648. nWriteBytes = 0;
  649. nTransmitBytes = 0;
  650. readerThreadIsRunning = false;
  651. writerThreadIsRunning = false;
  652. stopReaderFlag = true;
  653. stopWriterFlag = true;
  654. errorText.clear();
  655. }
  656. bool Child::isFinishedWriting() const {
  657. return ( (0 == nWriteBytes) &&
  658. (0 == nTransmitBytes) );
  659. }
  660. bool Child::closeInput(std::string &errorString) {
  661. #ifdef _WIN32
  662. // Close if not already closed.
  663. if ( (NULL != inputHandle) &&
  664. (CloseHandle(inputHandle) == 0) ) {
  665. errorString += (errorString.empty() ? "" : "\n");
  666. errorString += "Error closing input to the child: " + getErrorText();
  667. return false;
  668. }
  669. // Closed successfully.
  670. inputHandle = NULL;
  671. return true;
  672. #else
  673. // Close if not already closed.
  674. if ( (-1 != inputFileDescriptor) &&
  675. (0 != ::close(inputFileDescriptor)) ) {
  676. errorString += (errorString.empty() ? "" : "\n");
  677. errorString += "Error closing input to the child: " + getErrorText();
  678. return false;
  679. }
  680. // Closed successfully.
  681. inputFileDescriptor = -1;
  682. return true;
  683. #endif
  684. }
  685. bool Child::closeOutput(std::string &errorString) {
  686. #ifdef _WIN32
  687. // Close if not already closed.
  688. if ( (NULL != outputHandle) &&
  689. (CloseHandle(outputHandle) == 0) ) {
  690. errorString += (errorString.empty() ? "" : "\n");
  691. errorString += "Error closing output to the child: " + getErrorText();
  692. return false;
  693. }
  694. // Closed successfully.
  695. outputHandle = NULL;
  696. return true;
  697. #else
  698. // Close if not already closed.
  699. if ( (-1 != outputFileDescriptor) &&
  700. (0 != ::close(outputFileDescriptor)) ) {
  701. errorString += (errorString.empty() ? "" : "\n");
  702. errorString += "Error closing output to the child: " + getErrorText();
  703. return false;
  704. }
  705. // Closed successfully.
  706. outputFileDescriptor = -1;
  707. return true;
  708. #endif
  709. }
  710. void Child::closeStdIn() {
  711. if (!childStarted) {
  712. throw std::logic_error("Child process was not started "
  713. "when close() was called");
  714. }
  715. // Stop writer thread. Note: None of the error conditions that
  716. // cause an exception to be thrown by join() can ever occur.
  717. stopWriterFlag = true;
  718. std::string errorString;
  719. if (!closeOutput(errorString)) {
  720. throw std::runtime_error(errorString);
  721. }
  722. if (writerThreadIsRunning) {
  723. writerThread.join();
  724. writerThreadIsRunning = false;
  725. }
  726. }
  727. void Child::close() {
  728. if (!childStarted) {
  729. throw std::logic_error("Child process was not started "
  730. "when close() was called");
  731. }
  732. // Stop the reader and writer threads. Note: None of the error
  733. // conditions that cause an exception to be thrown by join()
  734. // can ever occur.
  735. stopReaderFlag = true;
  736. stopWriterFlag = true;
  737. // Terminate the child if it's running.
  738. if (isRunning()) {
  739. std::string errorString;
  740. bool noErrorOccurred = true;
  741. #ifdef _WIN32
  742. // Ignore errors. Reason: Terminating a proces that doesn't
  743. // exist (e.g. has exited) gives an error.
  744. (void) TerminateProcess(childProcess, terminateExitCode);
  745. noErrorOccurred = noErrorOccurred && closeInput(errorString);
  746. noErrorOccurred = noErrorOccurred && closeOutput(errorString);
  747. #else
  748. noErrorOccurred = noErrorOccurred && closeInput(errorString);
  749. noErrorOccurred = noErrorOccurred && closeOutput(errorString);
  750. if (kill(childPid, SIGKILL) != 0) {
  751. errorString += (errorString.empty() ? "" : "\n");
  752. errorString += "Error terminating the child process: " +
  753. getErrorText();
  754. noErrorOccurred = false;
  755. } else if (waitpid(childPid, NULL, 0) != childPid) {
  756. errorString += (errorString.empty() ? "" : "\n");
  757. errorString += "Error waiting for the child process: " +
  758. getErrorText();
  759. noErrorOccurred = false;
  760. }
  761. #endif
  762. if (!noErrorOccurred) {
  763. throw std::runtime_error(errorString);
  764. }
  765. }
  766. if (readerThreadIsRunning) {
  767. readerThread.join();
  768. readerThreadIsRunning = false;
  769. }
  770. if (writerThreadIsRunning) {
  771. writerThread.join();
  772. writerThreadIsRunning = false;
  773. }
  774. // Reset.
  775. init();
  776. }
  777. bool Child::isRunning() const {
  778. return childStarted && !childExited && !childExitedInferred;
  779. }
  780. bool Child::errorOccurred(std::string &errorDescription) const {
  781. errorDescription = errorText;
  782. return !errorDescription.empty();
  783. }
  784. void Child::run() {
  785. if (childStarted) {
  786. throw std::logic_error("Child process was active when "
  787. "run() was called");
  788. }
  789. if (cmdArgs.empty()) {
  790. throw std::invalid_argument("A child executable must be specified.");
  791. }
  792. #ifdef _WIN32
  793. // Set the bInheritHandle flag so pipe handles are inherited.
  794. SECURITY_ATTRIBUTES securityAttributes;
  795. securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
  796. securityAttributes.bInheritHandle = true;
  797. securityAttributes.lpSecurityDescriptor = NULL;
  798. // Create a pipe for the child process's STDOUT.
  799. HANDLE childStdOutAtChild;
  800. HANDLE childStdOutAtParent;
  801. HANDLE childStdInAtChild;
  802. HANDLE childStdInAtParent;
  803. int bufferSize = 0;
  804. if (!CreatePipe(&childStdOutAtParent,
  805. &childStdOutAtChild,
  806. &securityAttributes,
  807. bufferSize)) {
  808. throw std::runtime_error("Error from CreatePipe for stdout: " +
  809. getErrorText());
  810. }
  811. // Ensure the read handle to the pipe for STDOUT is not inherited.
  812. int inheritFlag = 0;
  813. if (!SetHandleInformation(childStdOutAtParent,
  814. HANDLE_FLAG_INHERIT,
  815. inheritFlag) ) {
  816. throw std::runtime_error("Error from GetHandleInformation for stdout: " +
  817. getErrorText());
  818. }
  819. // Create a pipe for the child process's STDIN.
  820. if (! CreatePipe(&childStdInAtChild,
  821. &childStdInAtParent,
  822. &securityAttributes,
  823. bufferSize)) {
  824. throw std::runtime_error("Error from CreatePipe for stdin: " +
  825. getErrorText());
  826. }
  827. // Ensure the write handle to the pipe for STDIN is not inherited.
  828. if (!SetHandleInformation(childStdInAtParent,
  829. HANDLE_FLAG_INHERIT,
  830. inheritFlag)) {
  831. throw std::runtime_error("Error from GetHandleInformation for stdin: " +
  832. getErrorText());
  833. }
  834. // Set up members of the PROCESS_INFORMATION structure.
  835. PROCESS_INFORMATION processInfo;
  836. std::fill((char *) &processInfo,
  837. ((char *) &processInfo) + sizeof(PROCESS_INFORMATION),
  838. 0);
  839. // Set up members of the STARTUPINFO structure. This structure
  840. // specifies the STDIN and STDOUT handles for redirection.
  841. STARTUPINFO startInfo;
  842. std::fill((char *) &startInfo,
  843. ((char *) &startInfo) + sizeof(STARTUPINFO),
  844. 0);
  845. startInfo.cb = sizeof(STARTUPINFO);
  846. startInfo.hStdError = childStdOutAtChild;
  847. startInfo.hStdOutput = childStdOutAtChild;
  848. startInfo.hStdInput = childStdInAtChild;
  849. startInfo.dwFlags |= STARTF_USESTDHANDLES;
  850. // Assemble the command line.
  851. std::string cmdline;
  852. if (cmdArgs.size() == 1) {
  853. cmdline = cmdArgs[0];
  854. } else {
  855. // Append all but last command-line arguments.
  856. for (size_t i = 0; i < cmdArgs.size() - 1; i++) {
  857. cmdline += cmdArgs[i] + " ";
  858. }
  859. cmdline += cmdArgs.back(); // Append last command-line argument.
  860. }
  861. // Create the child process.
  862. bool status;
  863. status = CreateProcess(NULL,
  864. (char *) cmdline.c_str(),
  865. NULL, // process security attributes
  866. NULL, // primary thread security attributes
  867. true, // handles are inherited
  868. 0, // creation flags
  869. NULL, // use parent's environment
  870. NULL, // use parent's current directory
  871. &startInfo, // STARTUPINFO pointer
  872. &processInfo); // receives PROCESS_INFORMATION
  873. // If an error occurs, throw.
  874. if (!status ) {
  875. throw std::runtime_error("Error from CreateProcess with "
  876. "command line \"" + cmdline + "\": " +
  877. getErrorText());
  878. }
  879. // Save the handles for communicating with the child process.
  880. inputHandle = childStdOutAtParent;
  881. outputHandle = childStdInAtParent;
  882. // Save the handles to the child process and its primary thread.
  883. childProcess = processInfo.hProcess;
  884. childThread = processInfo.hThread;
  885. // Close the child's end of the pipes.
  886. if (!CloseHandle(childStdOutAtChild)) {
  887. throw std::runtime_error("Error closing the child process "
  888. "stdout handle: " + getErrorText());
  889. }
  890. if (!CloseHandle(childStdInAtChild)) {
  891. throw std::runtime_error("Error closing the child process "
  892. "stdin handle: " + getErrorText());
  893. }
  894. #else
  895. // Create the pipes for the stdin and stdout.
  896. int childStdInPipe[2];
  897. int childStdOutPipe[2];
  898. if (pipe(childStdInPipe) != 0) {
  899. throw std::runtime_error("Error creating pipe for stdin: " +
  900. getErrorText());
  901. }
  902. if (pipe(childStdOutPipe) != 0) {
  903. ::close(childStdInPipe[0]);
  904. ::close(childStdInPipe[1]);
  905. throw std::runtime_error("Error creating pipe for stdout: " +
  906. getErrorText());
  907. }
  908. // Create the child process.
  909. childPid = fork();
  910. if (-1 == childPid) {
  911. for (int i = 0; i < 2; i++) {
  912. ::close(childStdInPipe[i]);
  913. ::close(childStdOutPipe[i]);
  914. }
  915. throw std::runtime_error("Error creating child process: " +
  916. getErrorText());
  917. }
  918. if (0 == childPid) {
  919. // The child executes this. Redirect stdin.
  920. if (dup2(childStdInPipe[0], STDIN_FILENO) == -1) {
  921. std::string errMsg;
  922. // Send message to parent.
  923. errMsg = "Error redirecting stdin in the child: " + getErrorText();
  924. iDummy = ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  925. exit(-1);
  926. }
  927. // Redirect stdout.
  928. if (dup2(childStdOutPipe[1], STDOUT_FILENO) == -1) {
  929. std::string errMsg;
  930. // Send message to parent.
  931. errMsg = "Error redirecting stdout in the child: " + getErrorText();
  932. iDummy = ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  933. exit(-1);
  934. }
  935. if (dup2(childStdOutPipe[1], STDERR_FILENO) == -1) {
  936. std::string errMsg;
  937. // Send message to parent.
  938. errMsg = "Error redirecting stderr in the child: " + getErrorText();
  939. iDummy = ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  940. exit(-1);
  941. }
  942. // Close pipes.
  943. if ( (::close(childStdInPipe[0]) != 0) ||
  944. (::close(childStdInPipe[1]) != 0) ||
  945. (::close(childStdOutPipe[0]) != 0) ||
  946. (::close(childStdOutPipe[1]) != 0) ) {
  947. std::string errMsg;
  948. // Send message to parent.
  949. errMsg = "Error closing the pipes in the child: " + getErrorText();
  950. iDummy = ::write(STDOUT_FILENO, errMsg.data(), errMsg.size());
  951. exit(-1);
  952. }
  953. // Prepare the arguments.
  954. std::vector<const char *> execvArgv;
  955. for (auto &arg : cmdArgs) {
  956. execvArgv.push_back(arg.c_str());
  957. }
  958. execvArgv.push_back((char *) NULL);
  959. // Run the child process image.
  960. (void) execv(execvArgv[0], (char * const *) &(execvArgv[0]));
  961. // Error from exec.
  962. std::string errMsg;
  963. // Send message to parent.
  964. errMsg = "Error (from exec) running the command \"";
  965. errMsg += execvArgv[0];
  966. errMsg += "\": " + getErrorText();
  967. // Ignore return value of ::write().
  968. (void) (::write(STDOUT_FILENO, errMsg.data(), errMsg.size()) + 1);
  969. exit(-1);
  970. }
  971. // Provide the stream buffers with the file descriptors for
  972. // communicating with the child process.
  973. inputFileDescriptor = childStdOutPipe[0];
  974. outputFileDescriptor = childStdInPipe[1];
  975. // Close the child's end of the pipes.
  976. if ( (::close(childStdInPipe[0]) != 0) ||
  977. (::close(childStdOutPipe[1]) != 0) ) {
  978. std::string errMsg;
  979. throw std::runtime_error("Error closing child's end of pipes in "
  980. "the parent: " + getErrorText());
  981. }
  982. #endif
  983. childStarted = true;
  984. // Start the reader and writer threads.
  985. stopReaderFlag = false;
  986. stopWriterFlag = false;
  987. try {
  988. std::thread readerTemp(&Child::readFromChild, this);
  989. readerThread = std::move(readerTemp);
  990. } catch (std::exception &e) {
  991. throw std::runtime_error("Error starting reader thread: " +
  992. getErrorText());
  993. }
  994. try {
  995. std::thread writerTemp(&Child::writeToChild, this);
  996. writerThread = std::move(writerTemp);
  997. } catch (std::exception &e) {
  998. stopReaderFlag = true;
  999. stopWriterFlag = true;
  1000. readerThread.join();
  1001. throw std::runtime_error("Error starting writer thread: " +
  1002. getErrorText());
  1003. }
  1004. readerThreadIsRunning = true;
  1005. writerThreadIsRunning = true;
  1006. }
  1007. bool Child::isDone() {
  1008. if (childExited) {
  1009. return true;
  1010. }
  1011. if (!childStarted) {
  1012. throw std::logic_error("Child process was not started "
  1013. "when isDone() was called");
  1014. }
  1015. int result;
  1016. #ifdef _WIN32
  1017. if (!GetExitCodeProcess(childProcess, (LPDWORD) &result)) {
  1018. throw std::runtime_error("Error checking status of child process: " +
  1019. getErrorText());
  1020. }
  1021. if (STILL_ACTIVE == result) {
  1022. return false;
  1023. }
  1024. // Child process has exited. Save the exit code.
  1025. exitCode = result;
  1026. exitCodeObtainedFlag = true;
  1027. #else
  1028. int status = 0;
  1029. result = waitpid(childPid, &status, WNOHANG);
  1030. if (-1 == result) {
  1031. throw std::runtime_error("Error checking status of child process: " +
  1032. getErrorText());
  1033. } else if (0 == result) {
  1034. // Child is still running.
  1035. return false;
  1036. }
  1037. if (WIFEXITED(status)) {
  1038. // Child exited normally.
  1039. exitCode = WEXITSTATUS(status);
  1040. exitCodeObtainedFlag = true;
  1041. }
  1042. #endif
  1043. childExited = true;
  1044. // Stop threads.
  1045. stopReaderFlag = true;
  1046. stopWriterFlag = true;
  1047. if (readerThreadIsRunning) {
  1048. readerThread.join();
  1049. readerThreadIsRunning = false;
  1050. }
  1051. if (writerThreadIsRunning) {
  1052. writerThread.join();
  1053. writerThreadIsRunning = false;
  1054. }
  1055. return true;
  1056. }
  1057. int32_t Child::result() {
  1058. if (exitCodeObtainedFlag) {
  1059. return exitCode;
  1060. }
  1061. // Check whether the process is running, and get the exit code.
  1062. if (!isDone()) {
  1063. throw std::logic_error("Child process was still running "
  1064. "when result() was called");
  1065. }
  1066. // Child process has exited.
  1067. if (!exitCodeObtainedFlag) {
  1068. // Exit code is not available.
  1069. throw std::runtime_error("Child process has exited but the exit "
  1070. "code is not available");
  1071. }
  1072. return exitCode;
  1073. }
  1074. std::string Child::getErrorText() {
  1075. #ifdef _WIN32
  1076. LPVOID winMsgBuf;
  1077. DWORD lastError = GetLastError();
  1078. FormatMessage(
  1079. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1080. FORMAT_MESSAGE_FROM_SYSTEM |
  1081. FORMAT_MESSAGE_IGNORE_INSERTS,
  1082. NULL,
  1083. lastError,
  1084. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1085. (char *) &winMsgBuf,
  1086. 0, NULL );
  1087. std::string errMsg((char *) winMsgBuf);
  1088. LocalFree(winMsgBuf);
  1089. return errMsg;
  1090. #else
  1091. return strerror(errno);
  1092. #endif
  1093. }
  1094. void Child::readFromChild() {
  1095. std::vector<char> rxBuf(bufferCapacity);
  1096. CodeDweller::PollTimer pollTimer(nominalPollTime_ms, maximumPollTime_ms);
  1097. while (!stopReaderFlag) {
  1098. char *bufferPtr;
  1099. bufferPtr = &(rxBuf[0]);
  1100. // Blocking read from the child.
  1101. #ifdef _WIN32
  1102. DWORD nBytesRead, lastError;
  1103. try {
  1104. DWORD bytesAvailable;
  1105. if (!PeekNamedPipe(inputHandle,
  1106. NULL,
  1107. 0,
  1108. NULL,
  1109. &bytesAvailable,
  1110. NULL)) {
  1111. throw std::runtime_error("Error from PeekNamedPipe: " +
  1112. getErrorText());
  1113. }
  1114. // Is data available?
  1115. if (0 == bytesAvailable) {
  1116. // No. Wait and try again.
  1117. pollTimer.pause();
  1118. continue;
  1119. }
  1120. if (!ReadFile(inputHandle,
  1121. bufferPtr,
  1122. bufferCapacity,
  1123. &nBytesRead,
  1124. NULL)) {
  1125. if (stopReaderFlag) {
  1126. break;
  1127. }
  1128. // Broken pipe occurs when the child exits; this is not
  1129. // necessarily an error condition.
  1130. lastError = GetLastError();
  1131. if ( (ERROR_BROKEN_PIPE != lastError) &&
  1132. (ERROR_SUCCESS != lastError) ){
  1133. errorText = "Error reading from the child process: ";
  1134. errorText += getErrorText();
  1135. }
  1136. break;
  1137. }
  1138. } catch(...) {
  1139. // Some error occurred.
  1140. if (stopReaderFlag) {
  1141. break;
  1142. }
  1143. // Thread was not commanded to stop; output error: Broken pipe
  1144. // occurs when the child exits; this is not an error
  1145. // condition.
  1146. lastError = GetLastError();
  1147. if ( (ERROR_BROKEN_PIPE != lastError) &&
  1148. (ERROR_SUCCESS != lastError) ){
  1149. errorText = "Exception when reading from the child process: ";
  1150. errorText += getErrorText();
  1151. }
  1152. // Exit the thread.
  1153. break;
  1154. }
  1155. #else
  1156. fd_set readFd;
  1157. int retVal;
  1158. struct timeval timeout = {0, 0};
  1159. FD_ZERO(&readFd);
  1160. FD_SET(inputFileDescriptor, &readFd);
  1161. // Check if input is available.
  1162. retVal = select(inputFileDescriptor + 1, &readFd, NULL, NULL, &timeout);
  1163. if (-1 == retVal) {
  1164. throw std::runtime_error("Error from select() when reading from the "
  1165. "child process: " + getErrorText());
  1166. }
  1167. // Is data available?
  1168. if (0 == retVal) {
  1169. // No. Wait and try again.
  1170. pollTimer.pause();
  1171. continue;
  1172. }
  1173. ssize_t nBytesRead;
  1174. nBytesRead = ::read(inputFileDescriptor,
  1175. bufferPtr,
  1176. bufferCapacity);
  1177. if (-1 == nBytesRead) {
  1178. if (stopReaderFlag) {
  1179. break;
  1180. }
  1181. errorText = "Error reading from the child process: ";
  1182. errorText += getErrorText();
  1183. break;
  1184. } else if (0 == nBytesRead) {
  1185. // EOF; child exited.
  1186. childExitedInferred = true;
  1187. stopWriterFlag = true;
  1188. break;
  1189. }
  1190. #endif
  1191. // Copy to the shared read buffer.
  1192. while ((nBytesRead > 0) && !stopReaderFlag) {
  1193. int nBytesToPut, nBytesFree;
  1194. nBytesToPut = nBytesRead;
  1195. // Can be called in the reader thread without locking the
  1196. // mutex.
  1197. nBytesFree = readBuffer.nFree();
  1198. if (nBytesToPut > nBytesFree) {
  1199. nBytesToPut = nBytesFree;
  1200. }
  1201. if (nBytesToPut > 0) {
  1202. std::lock_guard<std::mutex> lock(readBufferMutex);
  1203. readBuffer.put(bufferPtr, nBytesToPut);
  1204. bufferPtr += nBytesToPut;
  1205. nBytesRead -= nBytesToPut;
  1206. pollTimer.reset();
  1207. } else {
  1208. pollTimer.pause();
  1209. }
  1210. }
  1211. }
  1212. }
  1213. void Child::writeToChild() {
  1214. #ifndef _WIN32
  1215. // Writing to a broken pipe raises SIGPIPE. Ignore that signal;
  1216. // the error is handled by the return value of ::write.
  1217. signal(SIGPIPE, SIG_IGN);
  1218. #endif
  1219. std::vector<char> localWriteBuffer(bufferCapacity);
  1220. size_t nLocalWriteBytes;
  1221. CodeDweller::PollTimer pollTimer(nominalPollTime_ms, maximumPollTime_ms);
  1222. while (!stopWriterFlag) {
  1223. char *bufferPtr;
  1224. // Poll for data in the shared write buffer.
  1225. while ((0 == nWriteBytes) && !stopWriterFlag) {
  1226. pollTimer.pause();
  1227. }
  1228. if (stopWriterFlag) {
  1229. goto exit;
  1230. }
  1231. // Copy from the shared write buffer.
  1232. {
  1233. std::lock_guard<std::mutex> lock(writeBufferMutex);
  1234. localWriteBuffer.swap(writeBuffer);
  1235. nLocalWriteBytes = nWriteBytes;
  1236. nWriteBytes = 0;
  1237. }
  1238. if (stopWriterFlag) {
  1239. goto exit;
  1240. }
  1241. pollTimer.reset();
  1242. // Blocking write to the child.
  1243. bufferPtr = &(localWriteBuffer[0]);
  1244. while (nLocalWriteBytes > 0) {
  1245. #ifdef _WIN32
  1246. DWORD nBytesWritten;
  1247. if (!WriteFile(outputHandle,
  1248. bufferPtr,
  1249. nLocalWriteBytes,
  1250. &nBytesWritten,
  1251. NULL)) {
  1252. if (stopWriterFlag) {
  1253. goto exit;
  1254. }
  1255. errorText = "Error writing to the child process: ";
  1256. errorText += getErrorText();
  1257. goto exit;
  1258. }
  1259. if (stopWriterFlag) {
  1260. goto exit;
  1261. }
  1262. #else
  1263. ssize_t nBytesWritten;
  1264. nBytesWritten = ::write(outputFileDescriptor,
  1265. bufferPtr,
  1266. nLocalWriteBytes);
  1267. if (stopWriterFlag) {
  1268. goto exit;
  1269. }
  1270. if (-1 == nBytesWritten) {
  1271. if (ENOSPC != errno) {
  1272. // Some error other than no space.
  1273. errorText = "Error writing to the child process: ";
  1274. errorText += getErrorText();
  1275. goto exit;
  1276. }
  1277. }
  1278. #endif
  1279. nLocalWriteBytes -= nBytesWritten;
  1280. bufferPtr += nBytesWritten;
  1281. }
  1282. }
  1283. exit: return;
  1284. }
  1285. }