Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

child.cpp 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  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. exitCodeObtainedFlag = false;
  645. exitCode = 0;
  646. readBuffer.clear();
  647. nWriteBytes = 0;
  648. nTransmitBytes = 0;
  649. readerThreadIsRunning = false;
  650. writerThreadIsRunning = false;
  651. stopReaderFlag = true;
  652. stopWriterFlag = true;
  653. errorText.clear();
  654. }
  655. bool Child::isFinishedWriting() const {
  656. return ( (0 == nWriteBytes) &&
  657. (0 == nTransmitBytes) );
  658. }
  659. bool Child::closeInput(std::string &errorString) {
  660. #ifdef _WIN32
  661. // Close if not already closed.
  662. if ( (NULL != inputHandle) &&
  663. (CloseHandle(inputHandle) == 0) ) {
  664. errorString += (errorString.empty() ? "" : "\n");
  665. errorString += "Error closing input to the child: " + getErrorText();
  666. return false;
  667. }
  668. // Closed successfully.
  669. inputHandle = NULL;
  670. return true;
  671. #else
  672. // Close if not already closed.
  673. if ( (-1 != inputFileDescriptor) &&
  674. (0 != ::close(inputFileDescriptor)) ) {
  675. errorString += (errorString.empty() ? "" : "\n");
  676. errorString += "Error closing input to the child: " + getErrorText();
  677. return false;
  678. }
  679. // Closed successfully.
  680. inputFileDescriptor = -1;
  681. return true;
  682. #endif
  683. }
  684. bool Child::closeOutput(std::string &errorString) {
  685. #ifdef _WIN32
  686. // Close if not already closed.
  687. if ( (NULL != outputHandle) &&
  688. (CloseHandle(outputHandle) == 0) ) {
  689. errorString += (errorString.empty() ? "" : "\n");
  690. errorString += "Error closing output to the child: " + getErrorText();
  691. return false;
  692. }
  693. // Closed successfully.
  694. outputHandle = NULL;
  695. return true;
  696. #else
  697. // Close if not already closed.
  698. if ( (-1 != outputFileDescriptor) &&
  699. (0 != ::close(outputFileDescriptor)) ) {
  700. errorString += (errorString.empty() ? "" : "\n");
  701. errorString += "Error closing output to the child: " + getErrorText();
  702. return false;
  703. }
  704. // Closed successfully.
  705. outputFileDescriptor = -1;
  706. return true;
  707. #endif
  708. }
  709. void Child::closeStdIn() {
  710. if (!childStarted) {
  711. throw std::logic_error("Child process was not started "
  712. "when close() was called");
  713. }
  714. // Stop writer thread. Note: None of the error conditions that
  715. // cause an exception to be thrown by join() can ever occur.
  716. stopWriterFlag = true;
  717. std::string errorString;
  718. if (!closeOutput(errorString)) {
  719. throw std::runtime_error(errorString);
  720. }
  721. if (writerThreadIsRunning) {
  722. writerThread.join();
  723. writerThreadIsRunning = false;
  724. }
  725. }
  726. void Child::close() {
  727. if (!childStarted) {
  728. throw std::logic_error("Child process was not started "
  729. "when close() was called");
  730. }
  731. // Stop the reader and writer threads. Note: None of the error
  732. // conditions that cause an exception to be thrown by join()
  733. // can ever occur.
  734. stopReaderFlag = true;
  735. stopWriterFlag = true;
  736. // Terminate the child if it's running.
  737. if (isRunning()) {
  738. std::string errorString;
  739. bool noErrorOccurred = true;
  740. #ifdef _WIN32
  741. // Ignore errors. Reason: Terminating a proces that doesn't
  742. // exist (e.g. has exited) gives an error.
  743. (void) TerminateProcess(childProcess, terminateExitCode);
  744. noErrorOccurred = noErrorOccurred && closeInput(errorString);
  745. noErrorOccurred = noErrorOccurred && closeOutput(errorString);
  746. #else
  747. noErrorOccurred = noErrorOccurred && closeInput(errorString);
  748. noErrorOccurred = noErrorOccurred && closeOutput(errorString);
  749. if (kill(childPid, SIGKILL) != 0) {
  750. errorString += (errorString.empty() ? "" : "\n");
  751. errorString += "Error terminating the child process: " +
  752. getErrorText();
  753. noErrorOccurred = false;
  754. } else if (waitpid(childPid, NULL, 0) != childPid) {
  755. errorString += (errorString.empty() ? "" : "\n");
  756. errorString += "Error waiting for the child process: " +
  757. getErrorText();
  758. noErrorOccurred = false;
  759. }
  760. #endif
  761. if (!noErrorOccurred) {
  762. throw std::runtime_error(errorString);
  763. }
  764. }
  765. if (readerThreadIsRunning) {
  766. readerThread.join();
  767. readerThreadIsRunning = false;
  768. }
  769. if (writerThreadIsRunning) {
  770. writerThread.join();
  771. writerThreadIsRunning = false;
  772. }
  773. // Reset.
  774. init();
  775. }
  776. bool Child::isRunning() const {
  777. return childStarted && !childExited;
  778. }
  779. bool Child::errorOccurred(std::string &errorDescription) const {
  780. errorDescription = errorText;
  781. return !errorDescription.empty();
  782. }
  783. void Child::run() {
  784. if (childStarted) {
  785. throw std::logic_error("Child process was active when "
  786. "run() was called");
  787. }
  788. if (cmdArgs.empty()) {
  789. throw std::invalid_argument("A child executable must be specified.");
  790. }
  791. #ifdef _WIN32
  792. // Set the bInheritHandle flag so pipe handles are inherited.
  793. SECURITY_ATTRIBUTES securityAttributes;
  794. securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
  795. securityAttributes.bInheritHandle = true;
  796. securityAttributes.lpSecurityDescriptor = NULL;
  797. // Create a pipe for the child process's STDOUT.
  798. HANDLE childStdOutAtChild;
  799. HANDLE childStdOutAtParent;
  800. HANDLE childStdInAtChild;
  801. HANDLE childStdInAtParent;
  802. int bufferSize = 0;
  803. if (!CreatePipe(&childStdOutAtParent,
  804. &childStdOutAtChild,
  805. &securityAttributes,
  806. bufferSize)) {
  807. throw std::runtime_error("Error from CreatePipe for stdout: " +
  808. getErrorText());
  809. }
  810. // Ensure the read handle to the pipe for STDOUT is not inherited.
  811. int inheritFlag = 0;
  812. if (!SetHandleInformation(childStdOutAtParent,
  813. HANDLE_FLAG_INHERIT,
  814. inheritFlag) ) {
  815. throw std::runtime_error("Error from GetHandleInformation for stdout: " +
  816. getErrorText());
  817. }
  818. // Create a pipe for the child process's STDIN.
  819. if (! CreatePipe(&childStdInAtChild,
  820. &childStdInAtParent,
  821. &securityAttributes,
  822. bufferSize)) {
  823. throw std::runtime_error("Error from CreatePipe for stdin: " +
  824. getErrorText());
  825. }
  826. // Ensure the write handle to the pipe for STDIN is not inherited.
  827. if (!SetHandleInformation(childStdInAtParent,
  828. HANDLE_FLAG_INHERIT,
  829. inheritFlag)) {
  830. throw std::runtime_error("Error from GetHandleInformation for stdin: " +
  831. getErrorText());
  832. }
  833. // Set up members of the PROCESS_INFORMATION structure.
  834. PROCESS_INFORMATION processInfo;
  835. std::fill((char *) &processInfo,
  836. ((char *) &processInfo) + sizeof(PROCESS_INFORMATION),
  837. 0);
  838. // Set up members of the STARTUPINFO structure. This structure
  839. // specifies the STDIN and STDOUT handles for redirection.
  840. STARTUPINFO startInfo;
  841. std::fill((char *) &startInfo,
  842. ((char *) &startInfo) + sizeof(STARTUPINFO),
  843. 0);
  844. startInfo.cb = sizeof(STARTUPINFO);
  845. startInfo.hStdError = childStdOutAtChild;
  846. startInfo.hStdOutput = childStdOutAtChild;
  847. startInfo.hStdInput = childStdInAtChild;
  848. startInfo.dwFlags |= STARTF_USESTDHANDLES;
  849. // Assemble the command line.
  850. std::string cmdline;
  851. if (cmdArgs.size() == 1) {
  852. cmdline = cmdArgs[0];
  853. } else {
  854. // Append all but last command-line arguments.
  855. for (size_t i = 0; i < cmdArgs.size() - 1; i++) {
  856. cmdline += cmdArgs[i] + " ";
  857. }
  858. cmdline += cmdArgs.back(); // Append last command-line argument.
  859. }
  860. // Create the child process.
  861. bool status;
  862. status = CreateProcess(NULL,
  863. (char *) cmdline.c_str(),
  864. NULL, // process security attributes
  865. NULL, // primary thread security attributes
  866. true, // handles are inherited
  867. 0, // creation flags
  868. NULL, // use parent's environment
  869. NULL, // use parent's current directory
  870. &startInfo, // STARTUPINFO pointer
  871. &processInfo); // receives PROCESS_INFORMATION
  872. // If an error occurs, exit the application.
  873. if (!status ) {
  874. throw std::runtime_error("Error from CreateProcess with "
  875. "command line \"" + cmdline + "\": " +
  876. getErrorText());
  877. }
  878. // Save the handles for communicating with the child process.
  879. inputHandle = childStdOutAtParent;
  880. outputHandle = childStdInAtParent;
  881. // Save the handles to the child process and its primary thread.
  882. childProcess = processInfo.hProcess;
  883. childThread = processInfo.hThread;
  884. // Close the child's end of the pipes.
  885. if (!CloseHandle(childStdOutAtChild)) {
  886. throw std::runtime_error("Error closing the child process "
  887. "stdout handle: " + getErrorText());
  888. }
  889. if (!CloseHandle(childStdInAtChild)) {
  890. throw std::runtime_error("Error closing the child process "
  891. "stdin handle: " + getErrorText());
  892. }
  893. #else
  894. // Create the pipes for the stdin and stdout.
  895. int childStdInPipe[2];
  896. int childStdOutPipe[2];
  897. if (pipe(childStdInPipe) != 0) {
  898. throw std::runtime_error("Error creating pipe for stdin: " +
  899. getErrorText());
  900. }
  901. if (pipe(childStdOutPipe) != 0) {
  902. ::close(childStdInPipe[0]);
  903. ::close(childStdInPipe[1]);
  904. throw std::runtime_error("Error creating pipe for stdout: " +
  905. getErrorText());
  906. }
  907. // Create the child process.
  908. childPid = fork();
  909. if (-1 == childPid) {
  910. for (int i = 0; i < 2; i++) {
  911. ::close(childStdInPipe[i]);
  912. ::close(childStdOutPipe[i]);
  913. }
  914. throw std::runtime_error("Error creating child process: " +
  915. getErrorText());
  916. }
  917. if (0 == childPid) {
  918. // The child executes this. Redirect stdin.
  919. if (dup2(childStdInPipe[0], STDIN_FILENO) == -1) {
  920. std::string errMsg;
  921. // Send message to parent.
  922. errMsg = "Error redirecting stdin in the child: " + getErrorText();
  923. iDummy = ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  924. exit(-1);
  925. }
  926. // Redirect stdout.
  927. if (dup2(childStdOutPipe[1], STDOUT_FILENO) == -1) {
  928. std::string errMsg;
  929. // Send message to parent.
  930. errMsg = "Error redirecting stdout in the child: " + getErrorText();
  931. iDummy = ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  932. exit(-1);
  933. }
  934. if (dup2(childStdOutPipe[1], STDERR_FILENO) == -1) {
  935. std::string errMsg;
  936. // Send message to parent.
  937. errMsg = "Error redirecting stderr in the child: " + getErrorText();
  938. iDummy = ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  939. exit(-1);
  940. }
  941. // Close pipes.
  942. if ( (::close(childStdInPipe[0]) != 0) ||
  943. (::close(childStdInPipe[1]) != 0) ||
  944. (::close(childStdOutPipe[0]) != 0) ||
  945. (::close(childStdOutPipe[1]) != 0) ) {
  946. std::string errMsg;
  947. // Send message to parent.
  948. errMsg = "Error closing the pipes in the child: " + getErrorText();
  949. iDummy = ::write(STDOUT_FILENO, errMsg.data(), errMsg.size());
  950. exit(-1);
  951. }
  952. // Prepare the arguments.
  953. std::vector<const char *> execvArgv;
  954. for (auto &arg : cmdArgs) {
  955. execvArgv.push_back(arg.c_str());
  956. }
  957. execvArgv.push_back((char *) NULL);
  958. // Run the child process image.
  959. (void) execv(execvArgv[0], (char * const *) &(execvArgv[0]));
  960. // Error from exec.
  961. std::string errMsg;
  962. // Send message to parent.
  963. errMsg = "Error (from exec) running the command \"";
  964. errMsg += execvArgv[0];
  965. errMsg += "\": " + getErrorText();
  966. // Ignore return value of ::write().
  967. (void) (::write(STDOUT_FILENO, errMsg.data(), errMsg.size()) + 1);
  968. exit(-1);
  969. }
  970. // Provide the stream buffers with the file descriptors for
  971. // communicating with the child process.
  972. inputFileDescriptor = childStdOutPipe[0];
  973. outputFileDescriptor = childStdInPipe[1];
  974. // Close the child's end of the pipes.
  975. if ( (::close(childStdInPipe[0]) != 0) ||
  976. (::close(childStdOutPipe[1]) != 0) ) {
  977. std::string errMsg;
  978. throw std::runtime_error("Error closing child's end of pipes in "
  979. "the parent: " + getErrorText());
  980. }
  981. #endif
  982. childStarted = true;
  983. // Start the reader and writer threads.
  984. stopReaderFlag = false;
  985. stopWriterFlag = false;
  986. try {
  987. std::thread readerTemp(&Child::readFromChild, this);
  988. readerThread = std::move(readerTemp);
  989. } catch (std::exception &e) {
  990. throw std::runtime_error("Error starting reader thread: " +
  991. getErrorText());
  992. }
  993. try {
  994. std::thread writerTemp(&Child::writeToChild, this);
  995. writerThread = std::move(writerTemp);
  996. } catch (std::exception &e) {
  997. stopReaderFlag = true;
  998. stopWriterFlag = true;
  999. readerThread.join();
  1000. throw std::runtime_error("Error starting writer thread: " +
  1001. getErrorText());
  1002. }
  1003. readerThreadIsRunning = true;
  1004. writerThreadIsRunning = true;
  1005. }
  1006. bool Child::isDone() {
  1007. if (childExited) {
  1008. return true;
  1009. }
  1010. if (!childStarted) {
  1011. throw std::logic_error("Child process was not started "
  1012. "when isDone() was called");
  1013. }
  1014. int result;
  1015. #ifdef _WIN32
  1016. if (!GetExitCodeProcess(childProcess, (LPDWORD) &result)) {
  1017. throw std::runtime_error("Error checking status of child process: " +
  1018. getErrorText());
  1019. }
  1020. if (STILL_ACTIVE == result) {
  1021. return false;
  1022. }
  1023. // Child process has exited. Save the exit code.
  1024. exitCode = result;
  1025. exitCodeObtainedFlag = true;
  1026. #else
  1027. int status = 0;
  1028. result = waitpid(childPid, &status, WNOHANG);
  1029. if (-1 == result) {
  1030. throw std::runtime_error("Error checking status of child process: " +
  1031. getErrorText());
  1032. } else if (0 == result) {
  1033. // Child is still running.
  1034. return false;
  1035. }
  1036. if (WIFEXITED(status)) {
  1037. // Child exited normally.
  1038. exitCode = WEXITSTATUS(status);
  1039. exitCodeObtainedFlag = true;
  1040. }
  1041. #endif
  1042. childExited = true;
  1043. // Stop threads.
  1044. stopReaderFlag = true;
  1045. stopWriterFlag = true;
  1046. if (readerThreadIsRunning) {
  1047. readerThread.join();
  1048. readerThreadIsRunning = false;
  1049. }
  1050. if (writerThreadIsRunning) {
  1051. writerThread.join();
  1052. writerThreadIsRunning = false;
  1053. }
  1054. return true;
  1055. }
  1056. int32_t Child::result() {
  1057. if (exitCodeObtainedFlag) {
  1058. return exitCode;
  1059. }
  1060. // Check whether the process is running, and get the exit code.
  1061. if (!isDone()) {
  1062. throw std::logic_error("Child process was still running "
  1063. "when result() was called");
  1064. }
  1065. // Child process has exited.
  1066. if (!exitCodeObtainedFlag) {
  1067. // Exit code is not available.
  1068. throw std::runtime_error("Child process has exited but the exit "
  1069. "code is not available");
  1070. }
  1071. return exitCode;
  1072. }
  1073. std::string Child::getErrorText() {
  1074. #ifdef _WIN32
  1075. LPVOID winMsgBuf;
  1076. DWORD lastError = GetLastError();
  1077. FormatMessage(
  1078. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1079. FORMAT_MESSAGE_FROM_SYSTEM |
  1080. FORMAT_MESSAGE_IGNORE_INSERTS,
  1081. NULL,
  1082. lastError,
  1083. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1084. (char *) &winMsgBuf,
  1085. 0, NULL );
  1086. std::string errMsg((char *) winMsgBuf);
  1087. LocalFree(winMsgBuf);
  1088. return errMsg;
  1089. #else
  1090. return strerror(errno);
  1091. #endif
  1092. }
  1093. void Child::readFromChild() {
  1094. std::vector<char> rxBuf(bufferCapacity);
  1095. CodeDweller::PollTimer pollTimer(nominalPollTime_ms, maximumPollTime_ms);
  1096. while (!stopReaderFlag) {
  1097. char *bufferPtr;
  1098. bufferPtr = &(rxBuf[0]);
  1099. // Blocking read from the child.
  1100. #ifdef _WIN32
  1101. DWORD nBytesRead;
  1102. if (!ReadFile(inputHandle,
  1103. bufferPtr,
  1104. bufferCapacity,
  1105. &nBytesRead,
  1106. NULL)) {
  1107. if (stopReaderFlag) {
  1108. break;
  1109. }
  1110. // Broken pipe occurs when the child exits; this is not
  1111. // necessarily an error condition.
  1112. if (GetLastError() != ERROR_BROKEN_PIPE) {
  1113. errorText = "Error reading from the child process: ";
  1114. errorText += getErrorText();
  1115. }
  1116. break;
  1117. }
  1118. #else
  1119. ssize_t nBytesRead;
  1120. nBytesRead = ::read(inputFileDescriptor,
  1121. bufferPtr,
  1122. bufferCapacity);
  1123. if (-1 == nBytesRead) {
  1124. if (stopReaderFlag) {
  1125. break;
  1126. }
  1127. errorText = "Error reading from the child process: ";
  1128. errorText += getErrorText();
  1129. break;
  1130. } else if (0 == nBytesRead) {
  1131. // EOF; child exited.
  1132. break;
  1133. }
  1134. #endif
  1135. // Copy to the shared read buffer.
  1136. while ((nBytesRead > 0) && !stopReaderFlag) {
  1137. int nBytesToPut, nBytesFree;
  1138. nBytesToPut = nBytesRead;
  1139. // Can be called in the reader thread without locking the
  1140. // mutex.
  1141. nBytesFree = readBuffer.nFree();
  1142. if (nBytesToPut > nBytesFree) {
  1143. nBytesToPut = nBytesFree;
  1144. }
  1145. if (nBytesToPut > 0) {
  1146. std::lock_guard<std::mutex> lock(readBufferMutex);
  1147. readBuffer.put(bufferPtr, nBytesToPut);
  1148. bufferPtr += nBytesToPut;
  1149. nBytesRead -= nBytesToPut;
  1150. pollTimer.reset();
  1151. } else {
  1152. pollTimer.pause();
  1153. }
  1154. }
  1155. }
  1156. }
  1157. void Child::writeToChild() {
  1158. std::vector<char> localWriteBuffer(bufferCapacity);
  1159. size_t nLocalWriteBytes;
  1160. CodeDweller::PollTimer pollTimer(nominalPollTime_ms, maximumPollTime_ms);
  1161. while (!stopWriterFlag) {
  1162. char *bufferPtr;
  1163. // Poll for data in the shared write buffer.
  1164. while ((0 == nWriteBytes) && !stopWriterFlag) {
  1165. pollTimer.pause();
  1166. }
  1167. if (stopWriterFlag) {
  1168. goto exit;
  1169. }
  1170. // Copy from the shared write buffer.
  1171. {
  1172. std::lock_guard<std::mutex> lock(writeBufferMutex);
  1173. localWriteBuffer.swap(writeBuffer);
  1174. nLocalWriteBytes = nWriteBytes;
  1175. nWriteBytes = 0;
  1176. }
  1177. if (stopWriterFlag) {
  1178. goto exit;
  1179. }
  1180. pollTimer.reset();
  1181. // Blocking write to the child.
  1182. bufferPtr = &(localWriteBuffer[0]);
  1183. while (nLocalWriteBytes > 0) {
  1184. #ifdef _WIN32
  1185. DWORD nBytesWritten;
  1186. if (!WriteFile(outputHandle,
  1187. bufferPtr,
  1188. nLocalWriteBytes,
  1189. &nBytesWritten,
  1190. NULL)) {
  1191. if (stopWriterFlag) {
  1192. goto exit;
  1193. }
  1194. errorText = "Error writing to the child process: ";
  1195. errorText += getErrorText();
  1196. goto exit;
  1197. }
  1198. if (stopWriterFlag) {
  1199. goto exit;
  1200. }
  1201. #else
  1202. ssize_t nBytesWritten;
  1203. nBytesWritten = ::write(outputFileDescriptor,
  1204. bufferPtr,
  1205. nLocalWriteBytes);
  1206. if (stopWriterFlag) {
  1207. goto exit;
  1208. }
  1209. if (-1 == nBytesWritten) {
  1210. if (ENOSPC != errno) {
  1211. // Some error other than no space.
  1212. errorText = "Error writing to the child process: ";
  1213. errorText += getErrorText();
  1214. goto exit;
  1215. }
  1216. }
  1217. #endif
  1218. nLocalWriteBytes -= nBytesWritten;
  1219. bufferPtr += nBytesWritten;
  1220. }
  1221. }
  1222. exit: return;
  1223. }
  1224. }