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

child.cpp 38KB

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