123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632 |
- // \file child.cpp
- //
- // Copyright (C) 2014 MicroNeil Research Corporation.
- //
- // This program is part of the MicroNeil Research Open Library Project. For
- // more information go to http://www.microneil.com/OpenLibrary/index.html
- //
- // This program is free software; you can redistribute it and/or modify it
- // under the terms of the GNU General Public License as published by the
- // Free Software Foundation; either version 2 of the License, or (at your
- // option) any later version.
- //
- // This program is distributed in the hope that it will be useful, but WITHOUT
- // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
- // more details.
- //
- // You should have received a copy of the GNU General Public License along with
- // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
- // Place, Suite 330, Boston, MA 02111-1307 USA
- //==============================================================================
-
- #ifndef _WIN32
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <signal.h>
- #include <sys/select.h>
-
- #include <cstring>
- #include <cerrno>
- #endif
-
- #include <stdexcept>
- #include <utility>
-
- #include "CodeDweller/timing.hpp"
- #include "CodeDweller/child.hpp"
-
- namespace CodeDweller {
-
- ChildStream::ChildStream(std::vector<std::string> const &args,
- size_t bufSize) :
- std::iostream(&childStreambuf),
- childStreambuf(bufSize),
- cmdArgs(args) {
-
- init();
- run();
-
- }
-
- ChildStream::ChildStream(std::string const &childpath, size_t bufSize) :
- std::iostream(&childStreambuf),
- childStreambuf(bufSize) {
-
- cmdArgs.push_back(childpath);
- init();
- run();
- }
-
- ChildStream::ChildStream(size_t bufSize) :
- std::iostream(&childStreambuf),
- childStreambuf(bufSize) {
-
- init();
- }
-
- ChildStream::~ChildStream() {
- try {
- close();
- } catch (std::exception &e) {
- ;
- }
- }
-
- void ChildStream::init() {
-
- childStarted = false;
- childExited = false;
- exitCodeObtainedFlag = false;
- exitCode = 0;
- }
-
- void ChildStream::open(std::vector<std::string> const &args) {
- cmdArgs = args;
- init();
- run();
- }
-
- void ChildStream::open(std::string const &childpath) {
- cmdArgs.clear();
- cmdArgs.push_back(childpath);
- init();
- run();
- }
-
- size_t ChildStream::numBytesAvailable() const {
-
- return childStreambuf.numBytesAvailable();
-
- }
-
- bool ChildStream::isRunning() const {
- return childStarted && !childExited;
- }
-
- void ChildStream::run() {
-
- if (childStarted) {
- throw std::logic_error("Child process was active when "
- "run() was called");
- }
-
- if (cmdArgs.empty()) {
- throw std::invalid_argument("A child executable must be specified.");
- }
-
- #ifdef _WIN32
- // Set the bInheritHandle flag so pipe handles are inherited.
- SECURITY_ATTRIBUTES securityAttributes;
-
- securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
- securityAttributes.bInheritHandle = true;
- securityAttributes.lpSecurityDescriptor = NULL;
-
- // Create a pipe for the child process's STDOUT.
- HANDLE childStdOutAtChild;
- HANDLE childStdOutAtParent;
- HANDLE childStdInAtChild;
- HANDLE childStdInAtParent;
- int bufferSize = 0;
-
- if (!CreatePipe(&childStdOutAtParent,
- &childStdOutAtChild,
- &securityAttributes,
- bufferSize)) {
- throw std::runtime_error("Error from CreatePipe for stdout: " +
- getErrorText());
- }
-
- // Ensure the read handle to the pipe for STDOUT is not inherited.
- int inheritFlag = 0;
- if (!SetHandleInformation(childStdOutAtParent,
- HANDLE_FLAG_INHERIT,
- inheritFlag) ) {
- throw std::runtime_error("Error from GetHandleInformation for stdout: " +
- getErrorText());
- }
-
- // Create a pipe for the child process's STDIN.
- if (! CreatePipe(&childStdInAtChild,
- &childStdInAtParent,
- &securityAttributes,
- bufferSize)) {
- throw std::runtime_error("Error from CreatePipe for stdin: " +
- getErrorText());
- }
-
- // Ensure the write handle to the pipe for STDIN is not inherited.
- if (!SetHandleInformation(childStdInAtParent,
- HANDLE_FLAG_INHERIT,
- inheritFlag)) {
- throw std::runtime_error("Error from GetHandleInformation for stdin: " +
- getErrorText());
- }
-
- // Set up members of the PROCESS_INFORMATION structure.
- PROCESS_INFORMATION processInfo;
-
- std::fill((char *) &processInfo,
- ((char *) &processInfo) + sizeof(PROCESS_INFORMATION),
- 0);
-
- // Set up members of the STARTUPINFO structure. This structure
- // specifies the STDIN and STDOUT handles for redirection.
- STARTUPINFO startInfo;
-
- std::fill((char *) &startInfo,
- ((char *) &startInfo) + sizeof(STARTUPINFO),
- 0);
- startInfo.cb = sizeof(STARTUPINFO);
- startInfo.hStdError = childStdOutAtChild;
- startInfo.hStdOutput = childStdOutAtChild;
- startInfo.hStdInput = childStdInAtChild;
- startInfo.dwFlags |= STARTF_USESTDHANDLES;
-
- // Assemble the command line.
- std::string cmdline;
-
- if (cmdArgs.size() == 1) {
- cmdline = cmdArgs[0];
- } else {
-
- // Append all but last command-line arguments.
- for (size_t i = 0; i < cmdArgs.size() - 1; i++) {
- cmdline += cmdArgs[i] + " ";
- }
- cmdline += cmdArgs.back(); // Append last command-line argument.
- }
-
- // Create the child process.
- bool status;
-
- status = CreateProcess(NULL,
- (char *) cmdline.c_str(),
- NULL, // process security attributes
- NULL, // primary thread security attributes
- true, // handles are inherited
- 0, // creation flags
- NULL, // use parent's environment
- NULL, // use parent's current directory
- &startInfo, // STARTUPINFO pointer
- &processInfo); // receives PROCESS_INFORMATION
-
- // If an error occurs, exit the application.
- if (!status ) {
- throw std::runtime_error("Error from CreateProcess with "
- "command line \"" + cmdline + "\": " +
- getErrorText());
- }
-
- // Provide the stream buffers with the handles for communicating
- // with the child process.
- childStreambuf.setInputHandle(childStdOutAtParent);
- childStreambuf.setOutputHandle(childStdInAtParent);
-
- // Save the handles to the child process and its primary thread.
- childProcess = processInfo.hProcess;
- childThread = processInfo.hThread;
-
- // Close the child's end of the pipes.
- if (!CloseHandle(childStdOutAtChild)) {
- throw std::runtime_error("Error closing the child process "
- "stdout handle: " + getErrorText());
- }
-
- if (!CloseHandle(childStdInAtChild)) {
- throw std::runtime_error("Error closing the child process "
- "stdin handle: " + getErrorText());
- }
-
- #else
-
- // Create the pipes for the stdin and stdout.
- int childStdInPipe[2];
- int childStdOutPipe[2];
-
- if (pipe(childStdInPipe) != 0) {
- throw std::runtime_error("Error creating pipe for stdin: " +
- getErrorText());
- }
- if (pipe(childStdOutPipe) != 0) {
- ::close(childStdInPipe[0]);
- ::close(childStdInPipe[1]);
- throw std::runtime_error("Error creating pipe for stdout: " +
- getErrorText());
- }
-
- // Create the child process.
- childPid = fork();
- if (-1 == childPid) {
- for (int i = 0; i < 2; i++) {
- ::close(childStdInPipe[i]);
- ::close(childStdOutPipe[i]);
- }
- throw std::runtime_error("Error creating child process: " +
- getErrorText());
- }
-
- if (0 == childPid) {
-
- // The child executes this. Redirect stdin.
- if (dup2(childStdInPipe[0], STDIN_FILENO) == -1) {
- std::string errMsg;
-
- // Send message to parent.
- errMsg = "Error redirecting stdin in the child: " + getErrorText();
- ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
- exit(-1);
- }
-
- // Redirect stdout.
- if (dup2(childStdOutPipe[1], STDOUT_FILENO) == -1) {
- std::string errMsg;
-
- // Send message to parent.
- errMsg = "Error redirecting stdout in the child: " + getErrorText();
- ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
- exit(-1);
- }
-
- // Close pipes.
- if ( (::close(childStdInPipe[0]) != 0) ||
- (::close(childStdInPipe[1]) != 0) ||
- (::close(childStdOutPipe[0]) != 0) ||
- (::close(childStdOutPipe[1]) != 0) ) {
- std::string errMsg;
-
- // Send message to parent.
- errMsg = "Error closing the pipes in the child: " + getErrorText();
- ::write(STDOUT_FILENO, errMsg.data(), errMsg.size());
- exit(-1);
-
- }
-
- // Prepare the arguments.
- std::vector<const char *> execvArgv;
-
- for (auto &arg : cmdArgs) {
- execvArgv.push_back(arg.c_str());
- }
- execvArgv.push_back((char *) NULL);
-
- // Run the child process image.
- (void) execv(execvArgv[0], (char * const *) &(execvArgv[0]));
-
- // Error from exec.
- std::string errMsg;
-
- // Send message to parent.
- errMsg = "Error from exec: " + getErrorText();
- ::write(STDOUT_FILENO, errMsg.data(), errMsg.size());
- exit(-1);
-
- }
-
- // Provide the stream buffers with the file descriptors for
- // communicating with the child process.
- childStreambuf.setInputFileDescriptor(childStdOutPipe[0]);
- childStreambuf.setOutputFileDescriptor(childStdInPipe[1]);
-
- // Close the child's end of the pipes.
- if ( (::close(childStdInPipe[0]) != 0) ||
- (::close(childStdOutPipe[1]) != 0) ) {
- std::string errMsg;
-
- throw std::runtime_error("Error closing child's end of pipes in "
- "the parent: " + getErrorText());
- }
-
- #endif
-
- childStarted = true;
-
- }
-
- void ChildStream::close() {
-
- if (!childStarted) {
- throw std::logic_error("Child process was not started "
- "when close() was called");
- }
-
- // Terminate the child if it's running.
- if (isRunning()) {
-
- std::string errorString;
- bool errorOccurred = false;
-
- #ifdef _WIN32
- // Ignore errors. Reason: Terminating a proces that doesn't
- // exist (e.g. has exited) gives an error.
- (void) TerminateProcess(childProcess, terminateExitCode);
- #else
- if (kill(childPid, SIGKILL) != 0) {
- errorString += (errorOccurred ? "\n" : "");
- errorString += "Error terminating the child process: " +
- getErrorText();
- errorOccurred = true;
- } else if (waitpid(childPid, NULL, 0) != childPid) {
- errorString += (errorOccurred ? "\n" : "");
- errorString += "Error waiting for the child process: " +
- getErrorText();
- errorOccurred = true;
- }
- #endif
-
- if (errorOccurred) {
- throw std::runtime_error(errorString);
- }
-
- }
-
- // Reset.
- init();
-
- }
-
- bool ChildStream::isDone() {
-
- if (childExited) {
-
- return true;
-
- }
-
- if (!childStarted) {
- throw std::logic_error("Child process was not started "
- "when isDone() was called");
- }
-
- int result;
-
- #ifdef _WIN32
- if (!GetExitCodeProcess(childProcess, (LPDWORD) &result)) {
- throw std::runtime_error("Error checking status of child process: " +
- getErrorText());
- }
-
- if (STILL_ACTIVE == result) {
-
- return false;
-
- }
-
- // Child process has exited. Save the exit code.
- exitCode = result;
- exitCodeObtainedFlag = true;
-
- #else
- int status = 0;
-
- result = waitpid(childPid, &status, WNOHANG);
- if (-1 == result) {
- throw std::runtime_error("Error checking status of child process: " +
- getErrorText());
- } else if (0 == result) {
-
- // Child is still running.
- return false;
-
- }
-
- if (WIFEXITED(status)) {
-
- // Child exited normally.
- exitCode = WEXITSTATUS(status);
- exitCodeObtainedFlag = true;
-
- }
-
- #endif
-
- childExited = true;
-
- return true;
-
- }
-
- int32_t ChildStream::result() {
-
- if (exitCodeObtainedFlag) {
-
- return exitCode;
-
- }
-
- // Check whether the process is running, and get the exit code.
- if (!isDone()) {
- throw std::logic_error("Child process was still running "
- "when result() was called");
- }
-
- // Child process has exited.
- if (!exitCodeObtainedFlag) {
-
- // Exit code is not available.
- throw std::runtime_error("Child process has exited but the exit "
- "code is not available");
-
- }
-
- return exitCode;
-
- }
-
- std::string ChildStream::getErrorText() {
-
- #ifdef _WIN32
- LPVOID winMsgBuf;
- DWORD lastError = GetLastError();
-
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- lastError,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (char *) &winMsgBuf,
- 0, NULL );
-
- std::string errMsg((char *) winMsgBuf);
-
- LocalFree(winMsgBuf);
- return errMsg;
- #else
- return strerror(errno);
- #endif
- }
-
- ChildStream::ChildStreambuf::ChildStreambuf(std::size_t bufSize) :
- #ifdef _WIN32
- inputHandle(0),
- outputHandle(0),
- #else
- inputFileDescriptor(-1),
- outputFileDescriptor(-1),
- #endif
- bufferSize(bufSize),
- readBuffer(bufferSize + 1),
- writeBuffer(bufferSize + 1) {
-
- // Read buffer initialization.
- char *end = &(readBuffer.front()) + readBuffer.size();
-
- // Indicate to underflow that underflow has not been called.
- setg(end, end, end);
-
- // Write buffer initialization.
- char *base = &(writeBuffer.front());
-
- // Indicate to overflow that overflow has not been called.
- setp(base, base + writeBuffer.size() - 1);
-
- }
-
- #ifdef _WIN32
- void ChildStream::ChildStreambuf::setInputHandle(HANDLE inHandle) {
-
- inputHandle = inHandle;
-
- }
- #else
- void ChildStream::ChildStreambuf::setInputFileDescriptor(int inFd) {
-
- inputFileDescriptor = inFd;
-
- }
- #endif
-
- size_t ChildStream::ChildStreambuf::numBytesAvailable() const {
-
- size_t nBytesAvailable = egptr() - gptr();
-
- #ifdef _WIN32
- DWORD lpTotalBytesAvail;
-
- if (!PeekNamedPipe(inputHandle,
- NULL,
- 0,
- NULL,
- &lpTotalBytesAvail,
- NULL)) {
- throw std::runtime_error("Error from PeekNamedPipe: " +
- getErrorText());
- }
-
- if (lpTotalBytesAvail > 0) {
- nBytesAvailable++;
- }
- #else
- fd_set readFd;
- int retVal;
- struct timeval timeout = {0, 0};
-
- FD_ZERO(&readFd);
- FD_SET(inputFileDescriptor, &readFd);
-
- // Check if input is available.
- retVal = select(inputFileDescriptor + 1, &readFd, NULL, NULL, &timeout);
-
- if (-1 == retVal) {
- throw std::runtime_error("Error from select(): " + getErrorText());
- } else if (retVal > 0) {
- nBytesAvailable++;
- }
- #endif
-
- return nBytesAvailable;
-
- }
-
- std::streambuf::int_type ChildStream::ChildStreambuf::underflow() {
-
- // Check for empty buffer.
- if (gptr() < egptr()) {
-
- // Not empty.
- return traits_type::to_int_type(*gptr());
-
- }
-
- // Need to fill the buffer.
- char *base = &(readBuffer.front());
- char *start = base;
-
- // Check whether this is the first fill.
- if (eback() == base) {
-
- // Not the first fill. Copy one putback character.
- *(eback()) = *(egptr() - 1);
- start++;
- }
-
- // start points to the start of the buffer. Fill buffer.
- #ifdef _WIN32
- DWORD nBytesRead;
-
- if (!ReadFile(inputHandle,
- start,
- readBuffer.size() - (start - base),
- &nBytesRead,
- NULL)) {
- return traits_type::eof();
- }
- #else
- ssize_t nBytesRead;
-
- nBytesRead = ::read(inputFileDescriptor,
- start,
- readBuffer.size() - (start - base));
- if (-1 == nBytesRead) {
- return traits_type::eof();
- }
- #endif
-
- // Check for EOF.
- if (0 == nBytesRead) {
- return traits_type::eof();
- }
-
- // Update buffer pointers.
- setg(base, start, start + nBytesRead);
-
- return traits_type::to_int_type(*gptr());
-
- }
-
- #ifdef _WIN32
- void ChildStream::ChildStreambuf::setOutputHandle(HANDLE outHandle) {
-
- outputHandle = outHandle;
-
- }
- #else
- void ChildStream::ChildStreambuf::setOutputFileDescriptor(int outFd) {
-
- outputFileDescriptor = outFd;
-
- }
- #endif
-
- void ChildStream::ChildStreambuf::flushBuffer() {
-
- // Write.
- std::ptrdiff_t nBytes = pptr() - pbase();
-
- #ifdef _WIN32
- DWORD nBytesWritten;
-
- if (!WriteFile(outputHandle,
- pbase(),
- nBytes,
- &nBytesWritten,
- NULL)) {
- // Clear the output buffer.
- pbump(-nBytes);
- throw std::runtime_error("Error writing to child process: " +
- getErrorText());
- }
- #else
- ssize_t nBytesWritten;
-
- nBytesWritten = ::write(outputFileDescriptor, pbase(), nBytes);
-
- #endif
-
- // Clear the output buffer.
- pbump(-nBytes);
-
- if (nBytes != nBytesWritten) {
- throw std::runtime_error("Not all data was written to to child "
- "process: " + getErrorText());
- }
-
- return;
-
- }
-
- std::streambuf::int_type ChildStream::ChildStreambuf::overflow(int_type ch) {
-
- // Check whether we're writing EOF.
- if (traits_type::eof() != ch) {
-
- // Not writing EOF.
- *(pptr()) = ch;
- pbump(1);
-
- // Write.
- flushBuffer();
-
- // Success.
- return ch;
-
- }
-
- return traits_type::eof();
-
- }
-
- int ChildStream::ChildStreambuf::sync() {
-
- flushBuffer(); // Throws exception on failure.
-
- // Success.
- return 1;
-
- }
-
- Child::CircularBuffer::CircularBuffer(size_t maxSize) :
- buffer(maxSize + 1),
- capacity(maxSize) {
-
- iBegin = 0;
- iEnd = 0;
- }
-
- bool Child::CircularBuffer::empty() const {
- return (iBegin == iEnd);
- }
-
- size_t Child::CircularBuffer::nUsed() const {
- return capacity - nFree();
- }
-
- void Child::CircularBuffer::clear() {
- iBegin = 0;
- iEnd = 0;
- }
-
- size_t Child::CircularBuffer::nFree() const {
-
- size_t iLocalBegin = iBegin;
-
- // Correct an invalid value.
- if (iLocalBegin >= capacity + 1) {
- iLocalBegin = 0;
- }
-
- if (iLocalBegin <= iEnd) {
- return capacity - (iEnd - iLocalBegin);
- }
- return iLocalBegin - iEnd - 1;
-
- }
-
- void Child::CircularBuffer::put(char const *ptr, size_t nBytes) {
-
- for (size_t i = 0; i < nBytes; i++) {
- buffer[iEnd] = *ptr;
- ptr++;
- nextIndex(iEnd);
- }
-
- }
-
- Child::Child(std::vector<std::string> const &args,
- size_t bufSize,
- std::uint16_t nominalAboveMinPollTime_ms,
- std::uint16_t deltaPollTime_ms) :
- bufferCapacity(bufSize),
- readBuffer(bufferCapacity),
- writeBuffer(bufferCapacity),
- nominalPollTime_ms(nominalAboveMinPollTime_ms +
- CodeDweller::MinimumSleeperTime),
- maximumPollTime_ms(nominalPollTime_ms + deltaPollTime_ms) {
-
- init();
- open(args);
- }
-
- Child::Child(std::string const &childpath,
- size_t bufSize,
- std::uint16_t nominalAboveMinPollTime_ms,
- std::uint16_t deltaPollTime_ms) :
- bufferCapacity(bufSize),
- readBuffer(bufferCapacity),
- writeBuffer(bufferCapacity),
- nominalPollTime_ms(nominalAboveMinPollTime_ms +
- CodeDweller::MinimumSleeperTime),
- maximumPollTime_ms(nominalPollTime_ms + deltaPollTime_ms) {
-
- init();
- open(childpath);
- }
-
- Child::Child(size_t bufSize,
- std::uint16_t nominalAboveMinPollTime_ms,
- std::uint16_t deltaPollTime_ms) :
- bufferCapacity(bufSize),
- readBuffer(bufferCapacity),
- writeBuffer(bufferCapacity),
- nominalPollTime_ms(nominalAboveMinPollTime_ms +
- CodeDweller::MinimumSleeperTime),
- maximumPollTime_ms(nominalPollTime_ms + deltaPollTime_ms) {
-
- init();
- }
-
- Child::~Child() {
- try {
- close();
- } catch (std::exception &e) {
- ;
- }
- }
-
- void Child::open(std::vector<std::string> const &args) {
- cmdArgs = args;
-
- if (isRunning()) {
- throw std::logic_error("The child process was already active.");
- }
-
- init();
- run();
- }
-
- void Child::open(std::string const &childpath) {
-
- if (isRunning()) {
- throw std::logic_error("The child process was already active.");
- }
-
- cmdArgs.clear();
- cmdArgs.push_back(childpath);
- init();
- run();
- }
-
- void Child::init() {
-
- childStarted = false;
- childExited = false;
- exitCodeObtainedFlag = false;
- exitCode = 0;
-
- readBuffer.clear();
- nWriteBytes = 0;
- nTransmitBytes = 0;
-
- readerThreadIsRunning = false;
- writerThreadIsRunning = false;
- stopReaderFlag = true;
- stopWriterFlag = true;
- errorText.clear();
-
- }
-
- bool Child::isFinishedWriting() const {
- return ( (0 == nWriteBytes) &&
- (0 == nTransmitBytes) );
- }
-
- bool Child::closeInput(std::string &errorString) {
-
- #ifdef _WIN32
- // Close if not already closed.
- if ( (NULL != inputHandle) &&
- (CloseHandle(inputHandle) == 0) ) {
- errorString += (errorString.empty() ? "" : "\n");
- errorString += "Error closing input to the child: " + getErrorText();
- return false;
- }
-
- // Closed successfully.
- inputHandle = NULL;
- return true;
- #else
- // Close if not already closed.
- if ( (-1 != inputFileDescriptor) &&
- (0 != ::close(inputFileDescriptor)) ) {
- errorString += (errorString.empty() ? "" : "\n");
- errorString += "Error closing input to the child: " + getErrorText();
- return false;
- }
-
- // Closed successfully.
- inputFileDescriptor = -1;
- return true;
- #endif
-
- }
-
- bool Child::closeOutput(std::string &errorString) {
-
- #ifdef _WIN32
- // Close if not already closed.
- if ( (NULL != outputHandle) &&
- (CloseHandle(outputHandle) == 0) ) {
- errorString += (errorString.empty() ? "" : "\n");
- errorString += "Error closing output to the child: " + getErrorText();
- return false;
- }
-
- // Closed successfully.
- outputHandle = NULL;
- return true;
- #else
- // Close if not already closed.
- if ( (-1 != outputFileDescriptor) &&
- (0 != ::close(outputFileDescriptor)) ) {
- errorString += (errorString.empty() ? "" : "\n");
- errorString += "Error closing output to the child: " + getErrorText();
- return false;
- }
-
- // Closed successfully.
- outputFileDescriptor = -1;
- return true;
- #endif
-
- }
-
- void Child::closeStdIn() {
-
- if (!childStarted) {
- throw std::logic_error("Child process was not started "
- "when close() was called");
- }
-
- // Stop writer thread. Note: None of the error conditions that
- // cause an exception to be thrown by join() can ever occur.
- stopWriterFlag = true;
-
- std::string errorString;
-
- if (!closeOutput(errorString)) {
- throw std::runtime_error(errorString);
- }
-
- if (writerThreadIsRunning) {
- writerThread.join();
- writerThreadIsRunning = false;
- }
-
- }
-
- void Child::close() {
-
- if (!childStarted) {
- throw std::logic_error("Child process was not started "
- "when close() was called");
- }
-
- // Stop the reader and writer threads. Note: None of the error
- // conditions that cause an exception to be thrown by join()
- // can ever occur.
- stopReaderFlag = true;
- stopWriterFlag = true;
-
- // Terminate the child if it's running.
- if (isRunning()) {
-
- std::string errorString;
- bool noErrorOccurred = true;
-
- #ifdef _WIN32
- // Ignore errors. Reason: Terminating a proces that doesn't
- // exist (e.g. has exited) gives an error.
- (void) TerminateProcess(childProcess, terminateExitCode);
-
- noErrorOccurred = noErrorOccurred && closeInput(errorString);
- noErrorOccurred = noErrorOccurred && closeOutput(errorString);
- #else
- noErrorOccurred = noErrorOccurred && closeInput(errorString);
- noErrorOccurred = noErrorOccurred && closeOutput(errorString);
-
- if (kill(childPid, SIGKILL) != 0) {
-
- errorString += (errorString.empty() ? "" : "\n");
- errorString += "Error terminating the child process: " +
- getErrorText();
- noErrorOccurred = false;
-
- } else if (waitpid(childPid, NULL, 0) != childPid) {
-
- errorString += (errorString.empty() ? "" : "\n");
- errorString += "Error waiting for the child process: " +
- getErrorText();
- noErrorOccurred = false;
-
- }
- #endif
-
- if (!noErrorOccurred) {
- throw std::runtime_error(errorString);
- }
-
- }
-
- if (readerThreadIsRunning) {
- readerThread.join();
- readerThreadIsRunning = false;
- }
-
- if (writerThreadIsRunning) {
- writerThread.join();
- writerThreadIsRunning = false;
- }
-
- // Reset.
- init();
-
- }
-
- bool Child::isRunning() const {
- return childStarted && !childExited;
- }
-
- bool Child::errorOccurred(std::string &errorDescription) const {
- errorDescription = errorText;
- return !errorDescription.empty();
- }
-
- void Child::run() {
-
- if (childStarted) {
- throw std::logic_error("Child process was active when "
- "run() was called");
- }
-
- if (cmdArgs.empty()) {
- throw std::invalid_argument("A child executable must be specified.");
- }
-
- #ifdef _WIN32
- // Set the bInheritHandle flag so pipe handles are inherited.
- SECURITY_ATTRIBUTES securityAttributes;
-
- securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
- securityAttributes.bInheritHandle = true;
- securityAttributes.lpSecurityDescriptor = NULL;
-
- // Create a pipe for the child process's STDOUT.
- HANDLE childStdOutAtChild;
- HANDLE childStdOutAtParent;
- HANDLE childStdInAtChild;
- HANDLE childStdInAtParent;
- int bufferSize = 0;
-
- if (!CreatePipe(&childStdOutAtParent,
- &childStdOutAtChild,
- &securityAttributes,
- bufferSize)) {
- throw std::runtime_error("Error from CreatePipe for stdout: " +
- getErrorText());
- }
-
- // Ensure the read handle to the pipe for STDOUT is not inherited.
- int inheritFlag = 0;
- if (!SetHandleInformation(childStdOutAtParent,
- HANDLE_FLAG_INHERIT,
- inheritFlag) ) {
- throw std::runtime_error("Error from GetHandleInformation for stdout: " +
- getErrorText());
- }
-
- // Create a pipe for the child process's STDIN.
- if (! CreatePipe(&childStdInAtChild,
- &childStdInAtParent,
- &securityAttributes,
- bufferSize)) {
- throw std::runtime_error("Error from CreatePipe for stdin: " +
- getErrorText());
- }
-
- // Ensure the write handle to the pipe for STDIN is not inherited.
- if (!SetHandleInformation(childStdInAtParent,
- HANDLE_FLAG_INHERIT,
- inheritFlag)) {
- throw std::runtime_error("Error from GetHandleInformation for stdin: " +
- getErrorText());
- }
-
- // Set up members of the PROCESS_INFORMATION structure.
- PROCESS_INFORMATION processInfo;
-
- std::fill((char *) &processInfo,
- ((char *) &processInfo) + sizeof(PROCESS_INFORMATION),
- 0);
-
- // Set up members of the STARTUPINFO structure. This structure
- // specifies the STDIN and STDOUT handles for redirection.
- STARTUPINFO startInfo;
-
- std::fill((char *) &startInfo,
- ((char *) &startInfo) + sizeof(STARTUPINFO),
- 0);
- startInfo.cb = sizeof(STARTUPINFO);
- startInfo.hStdError = childStdOutAtChild;
- startInfo.hStdOutput = childStdOutAtChild;
- startInfo.hStdInput = childStdInAtChild;
- startInfo.dwFlags |= STARTF_USESTDHANDLES;
-
- // Assemble the command line.
- std::string cmdline;
-
- if (cmdArgs.size() == 1) {
- cmdline = cmdArgs[0];
- } else {
-
- // Append all but last command-line arguments.
- for (size_t i = 0; i < cmdArgs.size() - 1; i++) {
- cmdline += cmdArgs[i] + " ";
- }
- cmdline += cmdArgs.back(); // Append last command-line argument.
- }
-
- // Create the child process.
- bool status;
-
- status = CreateProcess(NULL,
- (char *) cmdline.c_str(),
- NULL, // process security attributes
- NULL, // primary thread security attributes
- true, // handles are inherited
- 0, // creation flags
- NULL, // use parent's environment
- NULL, // use parent's current directory
- &startInfo, // STARTUPINFO pointer
- &processInfo); // receives PROCESS_INFORMATION
-
- // If an error occurs, exit the application.
- if (!status ) {
- throw std::runtime_error("Error from CreateProcess with "
- "command line \"" + cmdline + "\": " +
- getErrorText());
- }
-
- // Save the handles for communicating with the child process.
- inputHandle = childStdOutAtParent;
- outputHandle = childStdInAtParent;
-
- // Save the handles to the child process and its primary thread.
- childProcess = processInfo.hProcess;
- childThread = processInfo.hThread;
-
- // Close the child's end of the pipes.
- if (!CloseHandle(childStdOutAtChild)) {
- throw std::runtime_error("Error closing the child process "
- "stdout handle: " + getErrorText());
- }
-
- if (!CloseHandle(childStdInAtChild)) {
- throw std::runtime_error("Error closing the child process "
- "stdin handle: " + getErrorText());
- }
-
- #else
-
- // Create the pipes for the stdin and stdout.
- int childStdInPipe[2];
- int childStdOutPipe[2];
-
- if (pipe(childStdInPipe) != 0) {
- throw std::runtime_error("Error creating pipe for stdin: " +
- getErrorText());
- }
- if (pipe(childStdOutPipe) != 0) {
- ::close(childStdInPipe[0]);
- ::close(childStdInPipe[1]);
- throw std::runtime_error("Error creating pipe for stdout: " +
- getErrorText());
- }
-
- // Create the child process.
- childPid = fork();
- if (-1 == childPid) {
- for (int i = 0; i < 2; i++) {
- ::close(childStdInPipe[i]);
- ::close(childStdOutPipe[i]);
- }
- throw std::runtime_error("Error creating child process: " +
- getErrorText());
- }
-
- if (0 == childPid) {
-
- // The child executes this. Redirect stdin.
- if (dup2(childStdInPipe[0], STDIN_FILENO) == -1) {
- std::string errMsg;
-
- // Send message to parent.
- errMsg = "Error redirecting stdin in the child: " + getErrorText();
- ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
- exit(-1);
- }
-
- // Redirect stdout.
- if (dup2(childStdOutPipe[1], STDOUT_FILENO) == -1) {
- std::string errMsg;
-
- // Send message to parent.
- errMsg = "Error redirecting stdout in the child: " + getErrorText();
- ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
- exit(-1);
- }
-
- if (dup2(childStdOutPipe[1], STDERR_FILENO) == -1) {
- std::string errMsg;
-
- // Send message to parent.
- errMsg = "Error redirecting stderr in the child: " + getErrorText();
- ::write(childStdOutPipe[1], errMsg.data(), errMsg.size());
- exit(-1);
- }
-
- // Close pipes.
- if ( (::close(childStdInPipe[0]) != 0) ||
- (::close(childStdInPipe[1]) != 0) ||
- (::close(childStdOutPipe[0]) != 0) ||
- (::close(childStdOutPipe[1]) != 0) ) {
- std::string errMsg;
-
- // Send message to parent.
- errMsg = "Error closing the pipes in the child: " + getErrorText();
- ::write(STDOUT_FILENO, errMsg.data(), errMsg.size());
- exit(-1);
-
- }
-
- // Prepare the arguments.
- std::vector<const char *> execvArgv;
-
- for (auto &arg : cmdArgs) {
- execvArgv.push_back(arg.c_str());
- }
- execvArgv.push_back((char *) NULL);
-
- // Run the child process image.
- (void) execv(execvArgv[0], (char * const *) &(execvArgv[0]));
-
- // Error from exec.
- std::string errMsg;
-
- // Send message to parent.
- errMsg = "Error (from exec) running the command \"";
- errMsg += execvArgv[0];
- errMsg += ": " + getErrorText();
- ::write(STDOUT_FILENO, errMsg.data(), errMsg.size());
- exit(-1);
-
- }
-
- // Provide the stream buffers with the file descriptors for
- // communicating with the child process.
- inputFileDescriptor = childStdOutPipe[0];
- outputFileDescriptor = childStdInPipe[1];
-
- // Close the child's end of the pipes.
- if ( (::close(childStdInPipe[0]) != 0) ||
- (::close(childStdOutPipe[1]) != 0) ) {
- std::string errMsg;
-
- throw std::runtime_error("Error closing child's end of pipes in "
- "the parent: " + getErrorText());
- }
-
- #endif
-
- childStarted = true;
-
- // Start the reader and writer threads.
- stopReaderFlag = false;
- stopWriterFlag = false;
-
- try {
-
- std::thread readerTemp(&Child::readFromChild, this);
- readerThread = std::move(readerTemp);
-
- } catch (std::exception &e) {
-
- throw std::runtime_error("Error starting reader thread: " +
- getErrorText());
-
- }
-
- try {
-
- std::thread writerTemp(&Child::writeToChild, this);
- writerThread = std::move(writerTemp);
-
- } catch (std::exception &e) {
-
- stopReaderFlag = true;
- stopWriterFlag = true;
- readerThread.join();
-
- throw std::runtime_error("Error starting writer thread: " +
- getErrorText());
-
- }
-
- readerThreadIsRunning = true;
- writerThreadIsRunning = true;
-
- }
-
- bool Child::isDone() {
-
- if (childExited) {
-
- return true;
-
- }
-
- if (!childStarted) {
- throw std::logic_error("Child process was not started "
- "when isDone() was called");
- }
-
- int result;
-
- #ifdef _WIN32
- if (!GetExitCodeProcess(childProcess, (LPDWORD) &result)) {
- throw std::runtime_error("Error checking status of child process: " +
- getErrorText());
- }
-
- if (STILL_ACTIVE == result) {
-
- return false;
-
- }
-
- // Child process has exited. Save the exit code.
- exitCode = result;
- exitCodeObtainedFlag = true;
-
- #else
- int status = 0;
-
- result = waitpid(childPid, &status, WNOHANG);
- if (-1 == result) {
- throw std::runtime_error("Error checking status of child process: " +
- getErrorText());
- } else if (0 == result) {
-
- // Child is still running.
- return false;
-
- }
-
- if (WIFEXITED(status)) {
-
- // Child exited normally.
- exitCode = WEXITSTATUS(status);
- exitCodeObtainedFlag = true;
-
- }
-
- #endif
-
- childExited = true;
-
- // Stop threads.
- stopReaderFlag = true;
- stopWriterFlag = true;
- if (readerThreadIsRunning) {
- readerThread.join();
- readerThreadIsRunning = false;
- }
- if (writerThreadIsRunning) {
- writerThread.join();
- writerThreadIsRunning = false;
- }
-
- return true;
-
- }
-
- int32_t Child::result() {
-
- if (exitCodeObtainedFlag) {
-
- return exitCode;
-
- }
-
- // Check whether the process is running, and get the exit code.
- if (!isDone()) {
- throw std::logic_error("Child process was still running "
- "when result() was called");
- }
-
- // Child process has exited.
- if (!exitCodeObtainedFlag) {
-
- // Exit code is not available.
- throw std::runtime_error("Child process has exited but the exit "
- "code is not available");
-
- }
-
- return exitCode;
-
- }
-
- std::string Child::getErrorText() {
-
- #ifdef _WIN32
- LPVOID winMsgBuf;
- DWORD lastError = GetLastError();
-
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- lastError,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (char *) &winMsgBuf,
- 0, NULL );
-
- std::string errMsg((char *) winMsgBuf);
-
- LocalFree(winMsgBuf);
- return errMsg;
- #else
- return strerror(errno);
- #endif
- }
-
- void Child::readFromChild() {
-
- std::vector<char> rxBuf(bufferCapacity);
-
- CodeDweller::PollTimer pollTimer(nominalPollTime_ms, maximumPollTime_ms);
-
- while (!stopReaderFlag) {
-
- char *bufferPtr;
-
- bufferPtr = &(rxBuf[0]);
-
- // Blocking read from the child.
- #ifdef _WIN32
- DWORD nBytesRead;
-
- if (!ReadFile(inputHandle,
- bufferPtr,
- bufferCapacity,
- &nBytesRead,
- NULL)) {
-
- if (stopReaderFlag) {
- break;
- }
-
- // Broken pipe occurs when the child exits; this is not
- // necessarily an error condition.
- if (GetLastError() != ERROR_BROKEN_PIPE) {
-
- errorText = "Error reading from the child process: ";
- errorText += getErrorText();
-
- }
-
- break;
-
- }
- #else
- ssize_t nBytesRead;
-
- nBytesRead = ::read(inputFileDescriptor,
- bufferPtr,
- bufferCapacity);
- if (-1 == nBytesRead) {
-
- if (stopReaderFlag) {
- break;
- }
-
- errorText = "Error reading from the child process: ";
- errorText += getErrorText();
- break;
-
- } else if (0 == nBytesRead) {
-
- // EOF; child exited.
- break;
-
- }
- #endif
-
- // Copy to the shared read buffer.
- while ((nBytesRead > 0) && !stopReaderFlag) {
-
- int nBytesToPut, nBytesFree;
-
- nBytesToPut = nBytesRead;
-
- // Can be called in the reader thread without locking the
- // mutex.
- nBytesFree = readBuffer.nFree();
-
- if (nBytesToPut > nBytesFree) {
- nBytesToPut = nBytesFree;
- }
-
- if (nBytesToPut > 0) {
- std::lock_guard<std::mutex> lock(readBufferMutex);
-
- readBuffer.put(bufferPtr, nBytesToPut);
- bufferPtr += nBytesToPut;
- nBytesRead -= nBytesToPut;
-
- pollTimer.reset();
-
- } else {
- pollTimer.pause();
- }
-
- }
-
- }
-
- }
-
- void Child::writeToChild() {
-
- std::vector<char> localWriteBuffer(bufferCapacity);
- size_t nLocalWriteBytes;
-
- CodeDweller::PollTimer pollTimer(nominalPollTime_ms, maximumPollTime_ms);
-
- while (!stopWriterFlag) {
-
- char *bufferPtr;
-
- // Poll for data in the shared write buffer.
- while ((0 == nWriteBytes) && !stopWriterFlag) {
- pollTimer.pause();
- }
-
- if (stopWriterFlag) {
- goto exit;
- }
-
- // Copy from the shared write buffer.
- {
- std::lock_guard<std::mutex> lock(writeBufferMutex);
-
- localWriteBuffer.swap(writeBuffer);
- nLocalWriteBytes = nWriteBytes;
- nWriteBytes = 0;
- }
-
- if (stopWriterFlag) {
- goto exit;
- }
-
- pollTimer.reset();
-
- // Blocking write to the child.
- bufferPtr = &(localWriteBuffer[0]);
-
- while (nLocalWriteBytes > 0) {
-
- #ifdef _WIN32
- DWORD nBytesWritten;
-
- if (!WriteFile(outputHandle,
- bufferPtr,
- nLocalWriteBytes,
- &nBytesWritten,
- NULL)) {
-
- if (stopWriterFlag) {
- goto exit;
- }
-
- errorText = "Error writing to the child process: ";
- errorText += getErrorText();
- goto exit;
-
- }
-
- if (stopWriterFlag) {
- goto exit;
- }
- #else
- ssize_t nBytesWritten;
-
- nBytesWritten = ::write(outputFileDescriptor,
- bufferPtr,
- nLocalWriteBytes);
-
- if (stopWriterFlag) {
- goto exit;
- }
-
- if (-1 == nBytesWritten) {
-
- if (ENOSPC != errno) {
-
- // Some error other than no space.
- errorText = "Error writing to the child process: ";
- errorText += getErrorText();
- goto exit;
-
- }
-
- }
- #endif
-
- nLocalWriteBytes -= nBytesWritten;
- bufferPtr += nBytesWritten;
-
- }
-
- }
-
- exit: return;
-
- }
-
- }
|