Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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 <iostream> // Temporary.
  32. #include <stdexcept>
  33. #include "child.hpp"
  34. namespace CodeDweller {
  35. Child::Child(std::vector<std::string> args, size_t bufSize) :
  36. readStreambuf(bufSize),
  37. writeStreambuf(bufSize),
  38. reader(&readStreambuf),
  39. writer(&writeStreambuf),
  40. cmdArgs(args) {
  41. init();
  42. }
  43. Child::Child(std::string childpath, size_t bufSize) :
  44. readStreambuf(bufSize),
  45. writeStreambuf(bufSize),
  46. reader(&readStreambuf),
  47. writer(&writeStreambuf),
  48. cmdline(childpath) {
  49. cmdArgs.push_back(childpath);
  50. init();
  51. }
  52. Child::~Child() {
  53. // Close handles.
  54. }
  55. void
  56. Child::init() {
  57. if (cmdArgs.empty()) {
  58. throw std::invalid_argument("A child executable must be specified.");
  59. }
  60. reader.exceptions(std::istream::failbit | std::istream::badbit);
  61. writer.exceptions(std::ostream::failbit | std::ostream::badbit);
  62. childStarted = false;
  63. childExited = false;
  64. exitCodeObtainedFlag = false;
  65. exitCode = 0;
  66. }
  67. size_t
  68. Child::numBytesAvailable() const {
  69. return readStreambuf.numBytesAvailable();
  70. }
  71. void
  72. Child::run() {
  73. if (childStarted) {
  74. throw std::logic_error("Child process was active when "
  75. "run() was called");
  76. }
  77. #ifdef _WIN32
  78. // Set the bInheritHandle flag so pipe handles are inherited.
  79. SECURITY_ATTRIBUTES securityAttributes;
  80. securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
  81. securityAttributes.bInheritHandle = true;
  82. securityAttributes.lpSecurityDescriptor = NULL;
  83. // Create a pipe for the child process's STDOUT.
  84. HANDLE childStdOutAtChild;
  85. HANDLE childStdOutAtParent;
  86. HANDLE childStdInAtChild;
  87. HANDLE childStdInAtParent;
  88. int bufferSize = 0;
  89. if (!CreatePipe(&childStdOutAtParent,
  90. &childStdOutAtChild,
  91. &securityAttributes,
  92. bufferSize)) {
  93. throw std::runtime_error("Error from CreatePipe for stdout: " +
  94. getErrorText());
  95. }
  96. // Ensure the read handle to the pipe for STDOUT is not inherited.
  97. int inheritFlag = 0;
  98. if (!SetHandleInformation(childStdOutAtParent,
  99. HANDLE_FLAG_INHERIT,
  100. inheritFlag) ) {
  101. throw std::runtime_error("Error from GetHandleInformation for stdout: " +
  102. getErrorText());
  103. }
  104. // Create a pipe for the child process's STDIN.
  105. if (! CreatePipe(&childStdInAtChild,
  106. &childStdInAtParent,
  107. &securityAttributes,
  108. bufferSize)) {
  109. throw std::runtime_error("Error from CreatePipe for stdin: " +
  110. getErrorText());
  111. }
  112. // Ensure the write handle to the pipe for STDIN is not inherited.
  113. if (!SetHandleInformation(childStdInAtParent,
  114. HANDLE_FLAG_INHERIT,
  115. inheritFlag)) {
  116. throw std::runtime_error("Error from GetHandleInformation for stdin: " +
  117. getErrorText());
  118. }
  119. // Set up members of the PROCESS_INFORMATION structure.
  120. PROCESS_INFORMATION processInfo;
  121. std::fill((char *) &processInfo,
  122. ((char *) &processInfo) + sizeof(PROCESS_INFORMATION),
  123. 0);
  124. // Set up members of the STARTUPINFO structure. This structure
  125. // specifies the STDIN and STDOUT handles for redirection.
  126. STARTUPINFO startInfo;
  127. std::fill((char *) &startInfo,
  128. ((char *) &startInfo) + sizeof(STARTUPINFO),
  129. 0);
  130. startInfo.cb = sizeof(STARTUPINFO);
  131. startInfo.hStdError = childStdOutAtChild;
  132. startInfo.hStdOutput = childStdOutAtChild;
  133. startInfo.hStdInput = childStdInAtChild;
  134. startInfo.dwFlags |= STARTF_USESTDHANDLES;
  135. // Assemble the command line.
  136. std::string cmdline;
  137. if (cmdArgs.size() == 1) {
  138. cmdline = cmdArgs[0];
  139. } else {
  140. // Append all but last command-line arguments.
  141. for (size_t i = 0; i < cmdArgs.size() - 1; i++) {
  142. cmdline += cmdArgs[i] + " ";
  143. }
  144. cmdline += cmdArgs.back(); // Append last command-line argument.
  145. }
  146. // Create the child process.
  147. bool status;
  148. status = CreateProcess(NULL,
  149. (char *) cmdline.c_str(),
  150. NULL, // process security attributes
  151. NULL, // primary thread security attributes
  152. true, // handles are inherited
  153. 0, // creation flags
  154. NULL, // use parent's environment
  155. NULL, // use parent's current directory
  156. &startInfo, // STARTUPINFO pointer
  157. &processInfo); // receives PROCESS_INFORMATION
  158. // If an error occurs, exit the application.
  159. if (!status ) {
  160. throw std::runtime_error("Error from CreateProcess with "
  161. "command line \"" + cmdline + "\": " +
  162. getErrorText());
  163. }
  164. // Provide the stream buffers with the handles for communicating
  165. // with the child process.
  166. readStreambuf.setInputHandle(childStdOutAtParent);
  167. writeStreambuf.setOutputHandle(childStdInAtParent);
  168. // Save the handles to the child process and its primary thread.
  169. childProcess = processInfo.hProcess;
  170. childThread = processInfo.hThread;
  171. // Close the child's end of the pipes.
  172. if (!CloseHandle(childStdOutAtChild)) {
  173. throw std::runtime_error("Error closing the child process "
  174. "stdout handle: " + getErrorText());
  175. }
  176. if (!CloseHandle(childStdInAtChild)) {
  177. throw std::runtime_error("Error closing the child process "
  178. "stdin handle: " + getErrorText());
  179. }
  180. #else
  181. // Create the pipes for the stdin and stdout.
  182. int childStdInPipe[2];
  183. int childStdOutPipe[2];
  184. if (pipe(childStdInPipe) != 0) {
  185. throw std::runtime_error("Error creating pipe for stdin: " +
  186. getErrorText());
  187. }
  188. if (pipe(childStdOutPipe) != 0) {
  189. close(childStdInPipe[0]);
  190. close(childStdInPipe[1]);
  191. throw std::runtime_error("Error creating pipe for stdout: " +
  192. getErrorText());
  193. }
  194. // Create the child process.
  195. childPid = fork();
  196. if (-1 == childPid) {
  197. for (int i = 0; i < 2; i++) {
  198. close(childStdInPipe[i]);
  199. close(childStdOutPipe[i]);
  200. }
  201. throw std::runtime_error("Error creating child process: " +
  202. getErrorText());
  203. }
  204. if (0 == childPid) {
  205. // The child executes this. Redirect stdin.
  206. if (dup2(childStdInPipe[0], STDIN_FILENO) == -1) {
  207. std::string errMsg;
  208. // Send message to parent.
  209. errMsg = "Error redirecting stdin in the child: " + getErrorText();
  210. write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  211. exit(-1);
  212. }
  213. // Redirect stdout.
  214. if (dup2(childStdOutPipe[1], STDOUT_FILENO) == -1) {
  215. std::string errMsg;
  216. // Send message to parent.
  217. errMsg = "Error redirecting stdout in the child: " + getErrorText();
  218. write(childStdOutPipe[1], errMsg.data(), errMsg.size());
  219. exit(-1);
  220. }
  221. // Close pipes.
  222. if ( (close(childStdInPipe[0]) != 0) ||
  223. (close(childStdInPipe[1]) != 0) ||
  224. (close(childStdOutPipe[0]) != 0) ||
  225. (close(childStdOutPipe[1]) != 0) ) {
  226. std::string errMsg;
  227. // Send message to parent.
  228. errMsg = "Error closing the pipes in the child: " + getErrorText();
  229. write(STDOUT_FILENO, errMsg.data(), errMsg.size());
  230. exit(-1);
  231. }
  232. // Prepare the arguments.
  233. std::vector<const char *> execvArgv;
  234. for (auto &arg : cmdArgs) {
  235. execvArgv.push_back(arg.c_str());
  236. }
  237. execvArgv.push_back((char *) NULL);
  238. // Run the child process image.
  239. (void) execv(execvArgv[0], (char * const *) &(execvArgv[0]));
  240. // Error from exec.
  241. std::string errMsg;
  242. // Send message to parent.
  243. errMsg = "Error from exec: " + getErrorText();
  244. write(STDOUT_FILENO, errMsg.data(), errMsg.size());
  245. exit(-1);
  246. }
  247. // std::cout << "Child pid: " << childPid << std::endl; // DEBUG.
  248. // Provide the stream buffers with the file descriptors for
  249. // communicating with the child process.
  250. readStreambuf.setInputFileDescriptor(childStdOutPipe[0]);
  251. writeStreambuf.setOutputFileDescriptor(childStdInPipe[1]);
  252. // Close the child's end of the pipes.
  253. if ( (close(childStdInPipe[0]) != 0) ||
  254. (close(childStdOutPipe[1]) != 0) ) {
  255. std::string errMsg;
  256. throw std::runtime_error("Error closing child's end of pipes in "
  257. "the parent: " + getErrorText());
  258. }
  259. #endif
  260. childStarted = true;
  261. }
  262. void
  263. Child::terminate() {
  264. if (isDone()) {
  265. return;
  266. }
  267. #ifdef _WIN32
  268. if (!TerminateProcess(childProcess, terminateExitCode)) {
  269. #else
  270. if (kill(childPid, SIGTERM) != 0) {
  271. #endif
  272. throw std::runtime_error("Error terminating the child process: " +
  273. getErrorText());
  274. }
  275. }
  276. bool
  277. Child::isDone() {
  278. if (childExited) {
  279. return true;
  280. }
  281. if (!childStarted) {
  282. throw std::logic_error("Child process was not started "
  283. "when isDone() was called");
  284. }
  285. int result;
  286. #ifdef _WIN32
  287. if (!GetExitCodeProcess(childProcess, (LPDWORD) &result)) {
  288. throw std::runtime_error("Error checking status of child process: " +
  289. getErrorText());
  290. }
  291. if (STILL_ACTIVE == result) {
  292. return false;
  293. }
  294. // Child process has exited. Save the exit code.
  295. exitCode = result;
  296. exitCodeObtainedFlag = true;
  297. #else
  298. int status = 0;
  299. result = waitpid(childPid, &status, WNOHANG);
  300. // std::cout << "isDone(). waitpid(" << childPid << ",...) returned " << result << std::endl; // DEBUG
  301. if (-1 == result) {
  302. throw std::runtime_error("Error checking status of child process: " +
  303. getErrorText());
  304. } else if (0 == result) {
  305. // Child is still running.
  306. // std::cout << "isDone(). Child is still running..." << std::endl; // DEBUG.
  307. return false;
  308. }
  309. // std::cout << "isDone(). Child exited." << std::endl; // DEBUG.
  310. if (WIFEXITED(status)) {
  311. // Child exited normally.
  312. exitCode = WEXITSTATUS(status);
  313. exitCodeObtainedFlag = true;
  314. //std::cout << "isDone(). Child exited normally. Exit code: " << exitCode << std::endl; // DEBUG.
  315. }
  316. #endif
  317. childExited = true;
  318. return true;
  319. }
  320. int32_t
  321. Child::result() {
  322. if (exitCodeObtainedFlag) {
  323. return exitCode;
  324. }
  325. // Check whether the process is running, and get the exit code.
  326. if (!isDone()) {
  327. throw std::logic_error("Child process was still running "
  328. "when result() was called");
  329. }
  330. // Child process has exited.
  331. if (!exitCodeObtainedFlag) {
  332. // Exit code is not available.
  333. throw std::runtime_error("Child process has exited but the exit "
  334. "code is not available");
  335. }
  336. return exitCode;
  337. }
  338. std::string
  339. Child::getErrorText() {
  340. #ifdef _WIN32
  341. LPVOID winMsgBuf;
  342. DWORD lastError = GetLastError();
  343. FormatMessage(
  344. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  345. FORMAT_MESSAGE_FROM_SYSTEM |
  346. FORMAT_MESSAGE_IGNORE_INSERTS,
  347. NULL,
  348. lastError,
  349. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  350. (char *) &winMsgBuf,
  351. 0, NULL );
  352. std::string errMsg((char *) winMsgBuf);
  353. LocalFree(winMsgBuf);
  354. return errMsg;
  355. #else
  356. return strerror(errno);
  357. #endif
  358. }
  359. Child::ReadStreambuf::ReadStreambuf(std::size_t bufferSize) :
  360. #ifdef _WIN32
  361. inputHandle(0),
  362. #else
  363. inputFileDescriptor(-1),
  364. #endif
  365. buffer(bufferSize + 1) {
  366. char *end = &(buffer.front()) + buffer.size();
  367. // Indicate to underflow that underflow has not been called.
  368. setg(end, end, end);
  369. }
  370. #ifdef _WIN32
  371. void
  372. Child::ReadStreambuf::setInputHandle(HANDLE inHandle) {
  373. inputHandle = inHandle;
  374. }
  375. #else
  376. void
  377. Child::ReadStreambuf::setInputFileDescriptor(int inFd) {
  378. inputFileDescriptor = inFd;
  379. }
  380. #endif
  381. size_t
  382. Child::ReadStreambuf::numBytesAvailable() const {
  383. size_t nBytesAvailable = egptr() - gptr();
  384. fd_set readFd;
  385. int retVal;
  386. struct timeval timeout = {0, 0};
  387. FD_ZERO(&readFd);
  388. FD_SET(inputFileDescriptor, &readFd);
  389. // Check if input is available.
  390. retVal = select(inputFileDescriptor + 1, &readFd, NULL, NULL, &timeout);
  391. if (-1 == retVal) {
  392. throw std::runtime_error("Error from select(): " + getErrorText());
  393. } else if (retVal > 0) {
  394. nBytesAvailable++;
  395. }
  396. return nBytesAvailable;
  397. }
  398. std::streambuf::int_type
  399. Child::ReadStreambuf::underflow() {
  400. std::cout << "underflow()." << std::endl; // debug
  401. // Check for empty buffer.
  402. if (gptr() < egptr()) {
  403. // Not empty.
  404. return traits_type::to_int_type(*gptr());
  405. }
  406. std::cout << "need to fill buffer." << std::endl; // debug
  407. // Need to fill the buffer.
  408. char *base = &(buffer.front());
  409. char *start = base;
  410. // Check whether this is the first fill.
  411. if (eback() == base) {
  412. // Not the first fill. Copy one putback character.
  413. *(eback()) = *(egptr() - 1);
  414. start++;
  415. }
  416. // start points to the start of the buffer. Fill buffer.
  417. #ifdef _WIN32
  418. DWORD nBytesRead;
  419. if (!ReadFile(inputHandle,
  420. start,
  421. buffer.size() - (start - base),
  422. &nBytesRead,
  423. NULL)) {
  424. return traits_type::eof();
  425. }
  426. #else
  427. ssize_t nBytesRead;
  428. std::cout << "Requesting read of " << buffer.size() - (start - base)
  429. << " bytes" << std::endl; // debug
  430. nBytesRead = read(inputFileDescriptor,
  431. start,
  432. buffer.size() - (start - base));
  433. // debug
  434. std::cout << "nBytesRead: " << nBytesRead << std::endl; // debug
  435. for (int i = 0; i < nBytesRead; i++) {
  436. std::cout << (char) start[i];
  437. }
  438. std::cout << std::endl;
  439. // end of debug
  440. if (-1 == nBytesRead) {
  441. return traits_type::eof();
  442. }
  443. #endif
  444. // Check for EOF.
  445. if (0 == nBytesRead) {
  446. return traits_type::eof();
  447. }
  448. // Update buffer pointers.
  449. setg(base, start, start + nBytesRead);
  450. std::cout << "underflow() return." << std::endl; // debug
  451. return traits_type::to_int_type(*gptr());
  452. }
  453. Child::WriteStreambuf::WriteStreambuf(std::size_t bufferSize) :
  454. #ifdef _WIN32
  455. outputHandle(0),
  456. #else
  457. outputFileDescriptor(-1),
  458. #endif
  459. buffer(bufferSize + 1) {
  460. char *base = &(buffer.front());
  461. // Indicate to overflow that overflow has not been called.
  462. setp(base, base + buffer.size() - 1);
  463. }
  464. #ifdef _WIN32
  465. void
  466. Child::WriteStreambuf::setOutputHandle(HANDLE outHandle) {
  467. outputHandle = outHandle;
  468. }
  469. #else
  470. void
  471. Child::WriteStreambuf::setOutputFileDescriptor(int outFd) {
  472. outputFileDescriptor = outFd;
  473. }
  474. #endif
  475. void
  476. Child::WriteStreambuf::flushBuffer() {
  477. // Write.
  478. std::ptrdiff_t nBytes = pptr() - pbase();
  479. #ifdef _WIN32
  480. DWORD nBytesWritten;
  481. if (!WriteFile(outputHandle,
  482. pbase(),
  483. nBytes,
  484. &nBytesWritten,
  485. NULL)) {
  486. // Clear the output buffer.
  487. pbump(-nBytes);
  488. throw std::runtime_error("Error writing to child process: " +
  489. getErrorText());
  490. }
  491. #else
  492. ssize_t nBytesWritten;
  493. nBytesWritten = write(outputFileDescriptor, pbase(), nBytes);
  494. // debug
  495. std::cout << "flushBuffer(). Requested to write " << nBytes << " bytes, "
  496. <<"wrote " << nBytesWritten << " bytes." << std::endl;
  497. char *ch = pbase();
  498. for (int i = 0; i < nBytesWritten; i++) {
  499. std::cout << (char) ch[i];
  500. }
  501. std::cout << std::endl;
  502. // end of debug.
  503. #endif
  504. // Clear the output buffer.
  505. pbump(-nBytes);
  506. if (nBytes != nBytesWritten) {
  507. throw std::runtime_error("Not all data was written to to child "
  508. "process: " + getErrorText());
  509. }
  510. return;
  511. }
  512. std::streambuf::int_type
  513. Child::WriteStreambuf::overflow(int_type ch) {
  514. // Check whether we're writing EOF.
  515. if (traits_type::eof() != ch) {
  516. // Not writing EOF.
  517. *(pptr()) = ch;
  518. pbump(1);
  519. // Write.
  520. flushBuffer();
  521. // Success.
  522. return ch;
  523. }
  524. return traits_type::eof();
  525. }
  526. int
  527. Child::WriteStreambuf::sync() {
  528. flushBuffer(); // Throws exception on failure.
  529. // Success.
  530. return 1;
  531. }
  532. }