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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  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. ::write(STDOUT_FILENO, errMsg.data(), errMsg.size());
  967. exit(-1);
  968. }
  969. // Provide the stream buffers with the file descriptors for
  970. // communicating with the child process.
  971. inputFileDescriptor = childStdOutPipe[0];
  972. outputFileDescriptor = childStdInPipe[1];
  973. // Close the child's end of the pipes.
  974. if ( (::close(childStdInPipe[0]) != 0) ||
  975. (::close(childStdOutPipe[1]) != 0) ) {
  976. std::string errMsg;
  977. throw std::runtime_error("Error closing child's end of pipes in "
  978. "the parent: " + getErrorText());
  979. }
  980. #endif
  981. childStarted = true;
  982. // Start the reader and writer threads.
  983. stopReaderFlag = false;
  984. stopWriterFlag = false;
  985. try {
  986. std::thread readerTemp(&Child::readFromChild, this);
  987. readerThread = std::move(readerTemp);
  988. } catch (std::exception &e) {
  989. throw std::runtime_error("Error starting reader thread: " +
  990. getErrorText());
  991. }
  992. try {
  993. std::thread writerTemp(&Child::writeToChild, this);
  994. writerThread = std::move(writerTemp);
  995. } catch (std::exception &e) {
  996. stopReaderFlag = true;
  997. stopWriterFlag = true;
  998. readerThread.join();
  999. throw std::runtime_error("Error starting writer thread: " +
  1000. getErrorText());
  1001. }
  1002. readerThreadIsRunning = true;
  1003. writerThreadIsRunning = true;
  1004. }
  1005. bool Child::isDone() {
  1006. if (childExited) {
  1007. return true;
  1008. }
  1009. if (!childStarted) {
  1010. throw std::logic_error("Child process was not started "
  1011. "when isDone() was called");
  1012. }
  1013. int result;
  1014. #ifdef _WIN32
  1015. if (!GetExitCodeProcess(childProcess, (LPDWORD) &result)) {
  1016. throw std::runtime_error("Error checking status of child process: " +
  1017. getErrorText());
  1018. }
  1019. if (STILL_ACTIVE == result) {
  1020. return false;
  1021. }
  1022. // Child process has exited. Save the exit code.
  1023. exitCode = result;
  1024. exitCodeObtainedFlag = true;
  1025. #else
  1026. int status = 0;
  1027. result = waitpid(childPid, &status, WNOHANG);
  1028. if (-1 == result) {
  1029. throw std::runtime_error("Error checking status of child process: " +
  1030. getErrorText());
  1031. } else if (0 == result) {
  1032. // Child is still running.
  1033. return false;
  1034. }
  1035. if (WIFEXITED(status)) {
  1036. // Child exited normally.
  1037. exitCode = WEXITSTATUS(status);
  1038. exitCodeObtainedFlag = true;
  1039. }
  1040. #endif
  1041. childExited = true;
  1042. // Stop threads.
  1043. stopReaderFlag = true;
  1044. stopWriterFlag = true;
  1045. if (readerThreadIsRunning) {
  1046. readerThread.join();
  1047. readerThreadIsRunning = false;
  1048. }
  1049. if (writerThreadIsRunning) {
  1050. writerThread.join();
  1051. writerThreadIsRunning = false;
  1052. }
  1053. return true;
  1054. }
  1055. int32_t Child::result() {
  1056. if (exitCodeObtainedFlag) {
  1057. return exitCode;
  1058. }
  1059. // Check whether the process is running, and get the exit code.
  1060. if (!isDone()) {
  1061. throw std::logic_error("Child process was still running "
  1062. "when result() was called");
  1063. }
  1064. // Child process has exited.
  1065. if (!exitCodeObtainedFlag) {
  1066. // Exit code is not available.
  1067. throw std::runtime_error("Child process has exited but the exit "
  1068. "code is not available");
  1069. }
  1070. return exitCode;
  1071. }
  1072. std::string Child::getErrorText() {
  1073. #ifdef _WIN32
  1074. LPVOID winMsgBuf;
  1075. DWORD lastError = GetLastError();
  1076. FormatMessage(
  1077. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  1078. FORMAT_MESSAGE_FROM_SYSTEM |
  1079. FORMAT_MESSAGE_IGNORE_INSERTS,
  1080. NULL,
  1081. lastError,
  1082. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1083. (char *) &winMsgBuf,
  1084. 0, NULL );
  1085. std::string errMsg((char *) winMsgBuf);
  1086. LocalFree(winMsgBuf);
  1087. return errMsg;
  1088. #else
  1089. return strerror(errno);
  1090. #endif
  1091. }
  1092. void Child::readFromChild() {
  1093. std::vector<char> rxBuf(bufferCapacity);
  1094. CodeDweller::PollTimer pollTimer(nominalPollTime_ms, maximumPollTime_ms);
  1095. while (!stopReaderFlag) {
  1096. char *bufferPtr;
  1097. bufferPtr = &(rxBuf[0]);
  1098. // Blocking read from the child.
  1099. #ifdef _WIN32
  1100. DWORD nBytesRead;
  1101. if (!ReadFile(inputHandle,
  1102. bufferPtr,
  1103. bufferCapacity,
  1104. &nBytesRead,
  1105. NULL)) {
  1106. if (stopReaderFlag) {
  1107. break;
  1108. }
  1109. // Broken pipe occurs when the child exits; this is not
  1110. // necessarily an error condition.
  1111. if (GetLastError() != ERROR_BROKEN_PIPE) {
  1112. errorText = "Error reading from the child process: ";
  1113. errorText += getErrorText();
  1114. }
  1115. break;
  1116. }
  1117. #else
  1118. ssize_t nBytesRead;
  1119. nBytesRead = ::read(inputFileDescriptor,
  1120. bufferPtr,
  1121. bufferCapacity);
  1122. if (-1 == nBytesRead) {
  1123. if (stopReaderFlag) {
  1124. break;
  1125. }
  1126. errorText = "Error reading from the child process: ";
  1127. errorText += getErrorText();
  1128. break;
  1129. } else if (0 == nBytesRead) {
  1130. // EOF; child exited.
  1131. break;
  1132. }
  1133. #endif
  1134. // Copy to the shared read buffer.
  1135. while ((nBytesRead > 0) && !stopReaderFlag) {
  1136. int nBytesToPut, nBytesFree;
  1137. nBytesToPut = nBytesRead;
  1138. // Can be called in the reader thread without locking the
  1139. // mutex.
  1140. nBytesFree = readBuffer.nFree();
  1141. if (nBytesToPut > nBytesFree) {
  1142. nBytesToPut = nBytesFree;
  1143. }
  1144. if (nBytesToPut > 0) {
  1145. std::lock_guard<std::mutex> lock(readBufferMutex);
  1146. readBuffer.put(bufferPtr, nBytesToPut);
  1147. bufferPtr += nBytesToPut;
  1148. nBytesRead -= nBytesToPut;
  1149. pollTimer.reset();
  1150. } else {
  1151. pollTimer.pause();
  1152. }
  1153. }
  1154. }
  1155. }
  1156. void Child::writeToChild() {
  1157. std::vector<char> localWriteBuffer(bufferCapacity);
  1158. size_t nLocalWriteBytes;
  1159. CodeDweller::PollTimer pollTimer(nominalPollTime_ms, maximumPollTime_ms);
  1160. while (!stopWriterFlag) {
  1161. char *bufferPtr;
  1162. // Poll for data in the shared write buffer.
  1163. while ((0 == nWriteBytes) && !stopWriterFlag) {
  1164. pollTimer.pause();
  1165. }
  1166. if (stopWriterFlag) {
  1167. goto exit;
  1168. }
  1169. // Copy from the shared write buffer.
  1170. {
  1171. std::lock_guard<std::mutex> lock(writeBufferMutex);
  1172. localWriteBuffer.swap(writeBuffer);
  1173. nLocalWriteBytes = nWriteBytes;
  1174. nWriteBytes = 0;
  1175. }
  1176. if (stopWriterFlag) {
  1177. goto exit;
  1178. }
  1179. pollTimer.reset();
  1180. // Blocking write to the child.
  1181. bufferPtr = &(localWriteBuffer[0]);
  1182. while (nLocalWriteBytes > 0) {
  1183. #ifdef _WIN32
  1184. DWORD nBytesWritten;
  1185. if (!WriteFile(outputHandle,
  1186. bufferPtr,
  1187. nLocalWriteBytes,
  1188. &nBytesWritten,
  1189. NULL)) {
  1190. if (stopWriterFlag) {
  1191. goto exit;
  1192. }
  1193. errorText = "Error writing to the child process: ";
  1194. errorText += getErrorText();
  1195. goto exit;
  1196. }
  1197. if (stopWriterFlag) {
  1198. goto exit;
  1199. }
  1200. #else
  1201. ssize_t nBytesWritten;
  1202. nBytesWritten = ::write(outputFileDescriptor,
  1203. bufferPtr,
  1204. nLocalWriteBytes);
  1205. if (stopWriterFlag) {
  1206. goto exit;
  1207. }
  1208. if (-1 == nBytesWritten) {
  1209. if (ENOSPC != errno) {
  1210. // Some error other than no space.
  1211. errorText = "Error writing to the child process: ";
  1212. errorText += getErrorText();
  1213. goto exit;
  1214. }
  1215. }
  1216. #endif
  1217. nLocalWriteBytes -= nBytesWritten;
  1218. bufferPtr += nBytesWritten;
  1219. }
  1220. }
  1221. exit: return;
  1222. }
  1223. }