Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

child.cpp 41KB

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