-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #ifndef WIN32
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <signal.h>
-
- #include <cstring>
- #include <cerrno>
- #endif
-
- #include <iostream> // Temporary.
- #include <stdexcept>
-
- #include "child.hpp"
-
- namespace CodeDweller {
-
- Child::Child(std::vector<std::string> args, size_t bufSize) :
- readStreambuf(bufSize),
- writeStreambuf(bufSize),
- reader(&readStreambuf),
- writer(&writeStreambuf),
- cmdArgs(args) {
-
- init();
-
- }
-
- Child::Child(std::string childpath, size_t bufSize) :
- readStreambuf(bufSize),
- writeStreambuf(bufSize),
- reader(&readStreambuf),
- writer(&writeStreambuf),
- cmdline(childpath) {
- cmdArgs.push_back(childpath);
- init();
- }
-
- Child::~Child() {
-
- }
-
- void
- Child::init() {
-
- if (cmdArgs.empty()) {
- throw std::invalid_argument("A child executable must be specified.");
- }
-
- reader.exceptions(std::istream::failbit | std::istream::badbit);
- writer.exceptions(std::ostream::failbit | std::ostream::badbit);
- childStarted = false;
- childExited = false;
- exitCodeObtainedFlag = false;
- exitCode = 0;
- }
-
- void
- Child::run() {
-
- if (childStarted) {
- throw std::logic_error("Child process was active when "
- "run() was called");
- }
-
- #ifdef WIN32
-
- SECURITY_ATTRIBUTES securityAttributes;
-
- securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
- securityAttributes.bInheritHandle = true;
- securityAttributes.lpSecurityDescriptor = NULL;
-
-
- 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());
- }
-
-
- int inheritFlag = 0;
- if (!SetHandleInformation(childStdOutAtParent,
- HANDLE_FLAG_INHERIT,
- inheritFlag) ) {
- throw std::runtime_error("Error from GetHandleInformation for stdout: " +
- getErrorText());
- }
-
-
- if (! CreatePipe(&childStdInAtChild,
- &childStdInAtParent,
- &securityAttributes,
- bufferSize)) {
- throw std::runtime_error("Error from CreatePipe for stdin: " +
- getErrorText());
- }
-
-
- if (!SetHandleInformation(childStdInAtParent,
- HANDLE_FLAG_INHERIT,
- inheritFlag)) {
- throw std::runtime_error("Error from GetHandleInformation for stdin: " +
- getErrorText());
- }
-
-
- PROCESS_INFORMATION processInfo;
-
- std::fill((char *) &processInfo,
- ((char *) &processInfo) + sizeof(PROCESS_INFORMATION),
- 0);
-
-
-
- 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;
-
-
- std::string cmdline;
-
- if (cmdArgs.size() == 1) {
- cmdline = cmdArgs[0];
- } else {
-
-
- for (size_t i = 0; i < cmdArgs.size() - 1; i++) {
- cmdline += cmdArgs[i] + " ";
- }
- cmdline += cmdArgs.back();
- }
-
-
- bool status;
-
- status = CreateProcess(NULL,
- (char *) cmdline.c_str(),
- NULL,
- NULL,
- true,
- 0,
- NULL,
- NULL,
- &startInfo,
- &processInfo);
-
-
- if (!status ) {
- throw std::runtime_error("Error from CreateProcess with "
- "command line \"" + cmdline + "\": " +
- getErrorText());
- }
-
-
-
- readStreambuf.setInputHandle(childStdOutAtParent);
- writeStreambuf.setOutputHandle(childStdInAtParent);
-
-
- childProcess = processInfo.hProcess;
- childThread = processInfo.hThread;
-
-
- 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
-
-
- 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());
- }
-
-
- 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) {
-
-
- if (dup2(childStdInPipe[0], STDIN_FILENO) == -1) {
- std::string errMsg;
-
-
- errMsg = "Error redirecting stdin in the child: " + getErrorText();
- write(childStdOutPipe[1], errMsg.data(), errMsg.size());
- exit(-1);
- }
-
-
- if (dup2(childStdOutPipe[1], STDOUT_FILENO) == -1) {
- std::string errMsg;
-
-
- errMsg = "Error redirecting stdout in the child: " + getErrorText();
- write(childStdOutPipe[1], errMsg.data(), errMsg.size());
- exit(-1);
- }
-
-
- if ( (close(childStdInPipe[0]) != 0) ||
- (close(childStdInPipe[1]) != 0) ||
- (close(childStdOutPipe[0]) != 0) ||
- (close(childStdOutPipe[1]) != 0) ) {
- std::string errMsg;
-
-
- errMsg = "Error closing the pipes in the child: " + getErrorText();
- write(STDOUT_FILENO, errMsg.data(), errMsg.size());
- exit(-1);
-
- }
-
-
- std::vector<const char *> execvArgv;
-
- for (auto &arg : cmdArgs) {
- execvArgv.push_back(arg.c_str());
- }
- execvArgv.push_back((char *) NULL);
-
-
- (void) execv(execvArgv[0], (char * const *) &(execvArgv[0]));
-
-
- std::string errMsg;
-
-
- errMsg = "Error from exec: " + getErrorText();
- write(STDOUT_FILENO, errMsg.data(), errMsg.size());
- exit(-1);
-
- }
-
-
-
-
-
- readStreambuf.setInputFileDescriptor(childStdOutPipe[0]);
- writeStreambuf.setOutputFileDescriptor(childStdInPipe[1]);
-
-
- 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
- Child::terminate() {
-
- if (isDone()) {
-
- return;
-
- }
-
- #ifdef WIN32
- if (!TerminateProcess(childProcess, terminateExitCode)) {
- #else
- if (kill(childPid, SIGTERM) != 0) {
- #endif
- throw std::runtime_error("Error terminating the child process: " +
- getErrorText());
- }
-
- }
-
- 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;
-
- }
-
-
- 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) {
-
-
-
- return false;
-
- }
-
-
- if (WIFEXITED(status)) {
-
-
- exitCode = WEXITSTATUS(status);
- exitCodeObtainedFlag = true;
-
-
- }
-
- #endif
-
- childExited = true;
-
- return true;
-
- }
-
- int32_t
- Child::result() {
-
- if (exitCodeObtainedFlag) {
-
- return exitCode;
-
- }
-
-
- if (!isDone()) {
- throw std::logic_error("Child process was still running"
- "when result() was called");
- }
-
-
- if (!exitCodeObtainedFlag) {
-
-
- 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
- }
-
- Child::ReadStreambuf::ReadStreambuf(std::size_t bufferSize) :
- #ifdef WIN32
- inputHandle(0),
- #else
- inputFileDescriptor(-1),
- #endif
- buffer(bufferSize + 1) {
-
- char *end = &(buffer.front()) + buffer.size();
-
-
- setg(end, end, end);
-
- }
-
- #ifdef WIN32
- void
- Child::ReadStreambuf::setInputHandle(HANDLE inHandle) {
-
- inputHandle = inHandle;
-
- }
- #else
- void
- Child::ReadStreambuf::setInputFileDescriptor(int inFd) {
-
- inputFileDescriptor = inFd;
-
- }
- #endif
-
- std::streambuf::int_type
- Child::ReadStreambuf::underflow() {
-
-
- if (gptr() < egptr()) {
-
-
- return traits_type::to_int_type(*gptr());
-
- }
-
-
- char *base = &(buffer.front());
- char *start = base;
-
-
- if (eback() == base) {
-
-
- *(eback()) = *(egptr() - 1);
- start++;
- }
-
-
- #ifdef WIN32
- DWORD nBytesRead;
-
- if (!ReadFile(inputHandle,
- start,
- buffer.size() - (start - base),
- &nBytesRead,
- NULL)) {
- return traits_type::eof();
- }
- #else
- ssize_t nBytesRead;
-
- nBytesRead = read(inputFileDescriptor,
- start,
- buffer.size() - (start - base));
- if (-1 == nBytesRead) {
- return traits_type::eof();
- }
- #endif
-
-
- if (0 == nBytesRead) {
- return traits_type::eof();
- }
-
-
- setg(base, start, start + nBytesRead);
-
- return traits_type::to_int_type(*gptr());
-
- }
-
- Child::WriteStreambuf::WriteStreambuf(std::size_t bufferSize) :
- #ifdef WIN32
- outputHandle(0),
- #else
- outputFileDescriptor(-1),
- #endif
- buffer(bufferSize + 1) {
-
- char *base = &(buffer.front());
-
-
- setp(base, base + buffer.size() - 1);
-
- }
-
- #ifdef WIN32
- void
- Child::WriteStreambuf::setOutputHandle(HANDLE outHandle) {
-
- outputHandle = outHandle;
-
- }
- #else
- void
- Child::WriteStreambuf::setOutputFileDescriptor(int outFd) {
-
- outputFileDescriptor = outFd;
-
- }
- #endif
-
- void
- Child::WriteStreambuf::flushBuffer() {
-
-
- std::ptrdiff_t nBytes = pptr() - pbase();
-
- #ifdef WIN32
- DWORD nBytesWritten;
-
- if (!WriteFile(outputHandle,
- pbase(),
- nBytes,
- &nBytesWritten,
- NULL)) {
-
- pbump(-nBytes);
- throw std::runtime_error("Error writing to child process: " +
- getErrorText());
- }
- #else
- ssize_t nBytesWritten;
-
- nBytesWritten = write(outputFileDescriptor, pbase(), nBytes);
-
- #endif
-
-
- pbump(-nBytes);
-
- if (nBytes != nBytesWritten) {
- throw std::runtime_error("Not all data was written to to child "
- "process: " + getErrorText());
- }
-
- return;
-
- }
-
- std::streambuf::int_type
- Child::WriteStreambuf::overflow(int_type ch) {
-
-
- if (traits_type::eof() != ch) {
-
-
- *(pptr()) = ch;
- pbump(1);
-
-
- flushBuffer();
-
-
- return ch;
-
- }
-
- return traits_type::eof();
-
- }
-
- int
- Child::WriteStreambuf::sync() {
-
- flushBuffer();
-
-
- return 1;
-
- }
-
- }
|