1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636 |
- // \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>
-
- /// Dummy used to suppressed warnings about unused values.
- int iDummy;
-
- #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();
- iDummy = ::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();
- iDummy = ::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();
- iDummy = ::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();
- iDummy = ::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();
- iDummy = ::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();
- iDummy = ::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();
- iDummy = ::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();
- iDummy = ::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();
- iDummy = ::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;
-
- }
-
- }
|