src/SystemProcess.h
branchv_0
changeset 29 6f15f18d2abf
parent 28 9172bd97ae99
child 30 56409232e1a1
equal deleted inserted replaced
28:9172bd97ae99 29:6f15f18d2abf
     1 /**
       
     2  * Relational pipes
       
     3  * Copyright © 2019 František Kučera (Frantovo.cz, GlobalCode.info)
       
     4  *
       
     5  * This program is free software: you can redistribute it and/or modify
       
     6  * it under the terms of the GNU General Public License as published by
       
     7  * the Free Software Foundation, version 3 of the License.
       
     8  *
       
     9  * This program is distributed in the hope that it will be useful,
       
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
       
    12  * GNU General Public License for more details.
       
    13  *
       
    14  * You should have received a copy of the GNU General Public License
       
    15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
       
    16  */
       
    17 #pragma once
       
    18 
       
    19 #include <vector>
       
    20 #include <sstream>
       
    21 #include <fcntl.h>
       
    22 #include <unistd.h>
       
    23 #include <sys/wait.h>
       
    24 #include <ext/stdio_filebuf.h>
       
    25 
       
    26 #include <relpipe/writer/typedefs.h>
       
    27 #include <relpipe/cli/RelpipeCLIException.h>
       
    28 
       
    29 namespace relpipe {
       
    30 namespace in {
       
    31 namespace filesystem {
       
    32 
       
    33 /**
       
    34  * Simple wrapper for a system process (fork+exec) that captures and returns just the STDOUT.
       
    35  */
       
    36 class SystemProcess {
       
    37 private:
       
    38 	/**
       
    39 	 * the command + its arguments
       
    40 	 */
       
    41 	std::vector<std::string> commandLine;
       
    42 	std::vector<std::string> environment;
       
    43 	int nullFile = -1;
       
    44 
       
    45 	/**
       
    46 	 * TODO: move to a common library (copied from the AWK module) 
       
    47 	 * @param args
       
    48 	 */
       
    49 	void execp(const std::vector<std::string>& args) {
       
    50 		const char** a = new const char*[args.size() + 1];
       
    51 		for (size_t i = 0; i < args.size(); i++) a[i] = args[i].c_str();
       
    52 		a[args.size()] = nullptr;
       
    53 
       
    54 		execvp(a[0], (char*const*) a);
       
    55 
       
    56 		delete[] a;
       
    57 		throw relpipe::cli::RelpipeCLIException(L"Unable to do execvp().", relpipe::cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exception?
       
    58 	}
       
    59 
       
    60 	/**
       
    61 	 * TODO: move to a common library (copied from the AWK module) 
       
    62 	 * @param readerFD
       
    63 	 * @param writerFD
       
    64 	 */
       
    65 	void createPipe(int& readerFD, int& writerFD) {
       
    66 		int fds[2];
       
    67 		int result = pipe(fds);
       
    68 		readerFD = fds[0];
       
    69 		writerFD = fds[1];
       
    70 		if (result < 0) throw relpipe::cli::RelpipeCLIException(L"Unable to create a pipe.", relpipe::cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exception?
       
    71 	}
       
    72 
       
    73 	/**
       
    74 	 * TODO: move to a common library (copied from the AWK module) 
       
    75 	 */
       
    76 	void redirectFD(int oldfd, int newfd) {
       
    77 		int result = dup2(oldfd, newfd);
       
    78 		if (result < 0) throw relpipe::cli::RelpipeCLIException(L"Unable redirect FD.", relpipe::cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exception?
       
    79 	}
       
    80 
       
    81 	/**
       
    82 	 * TODO: move to a common library (copied from the AWK module) 
       
    83 	 */
       
    84 	void closeOrThrow(int fd) {
       
    85 		int error = close(fd);
       
    86 		if (error) throw relpipe::cli::RelpipeCLIException(L"Unable to close FD: " + to_wstring(fd) + L" from PID: " + to_wstring(getpid()), relpipe::cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exception?
       
    87 	}
       
    88 
       
    89 public:
       
    90 
       
    91 	SystemProcess(const std::vector<std::string>& commandLine, const std::vector<std::string>& environment = {}) : commandLine(commandLine), environment(environment) {
       
    92 		nullFile = open("/dev/null", O_RDWR);
       
    93 	}
       
    94 
       
    95 	virtual ~SystemProcess() {
       
    96 		close(nullFile);
       
    97 	}
       
    98 
       
    99 	std::string execute() {
       
   100 
       
   101 		std::stringstream result;
       
   102 
       
   103 		// FIXME: different kinds of exception or return the exit code (now it enters infinite loop if the execp() fails)
       
   104 		// TODO: rename (not specific to hash)
       
   105 		int hashReaderFD;
       
   106 		int hashWriterFD;
       
   107 		createPipe(hashReaderFD, hashWriterFD);
       
   108 
       
   109 		__pid_t hashPid = fork();
       
   110 
       
   111 		if (hashPid < 0) {
       
   112 			throw relpipe::cli::RelpipeCLIException(L"Unable to fork the hash process.", relpipe::cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exception?
       
   113 		} else if (hashPid == 0) {
       
   114 			// Child process
       
   115 			closeOrThrow(hashReaderFD);
       
   116 			redirectFD(nullFile, STDIN_FILENO);
       
   117 			redirectFD(nullFile, STDERR_FILENO);
       
   118 			redirectFD(hashWriterFD, STDOUT_FILENO);
       
   119 			for (int i = 0; i < environment.size();) {
       
   120 				std::string name = environment[i++];
       
   121 				std::string value = environment[i++];
       
   122 				setenv(name.c_str(), value.c_str(), true);
       
   123 			}
       
   124 			execp(commandLine);
       
   125 		} else {
       
   126 			// Parent process
       
   127 			closeOrThrow(hashWriterFD);
       
   128 
       
   129 			__gnu_cxx::stdio_filebuf<char> hashReaderBuffer(hashReaderFD, std::ios::in);
       
   130 			std::istream hashReader(&hashReaderBuffer);
       
   131 
       
   132 			for (char ch; hashReader.read(&ch, 1).good();) result.put(ch);
       
   133 
       
   134 			int waitError;
       
   135 			__pid_t waitPID = wait(&waitError);
       
   136 			if (waitError) throw relpipe::cli::RelpipeCLIException(L"The child process returned an error exit code.", relpipe::cli::CLI::EXIT_CODE_UNEXPECTED_ERROR); // TODO: better exception?
       
   137 		}
       
   138 
       
   139 		return result.str();
       
   140 	}
       
   141 };
       
   142 
       
   143 }
       
   144 }
       
   145 }