您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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