Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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