diff --git a/src/process.cpp b/src/process.cpp index ed3624f..010d3b4 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -6,8 +6,11 @@ #include #include +#include #include +#include + namespace fws { CommandResult runCommand(const std::vector& arguments) { @@ -16,23 +19,44 @@ CommandResult runCommand(const std::vector& arguments) { return result; } - int pipeFds[2]; - if (pipe(pipeFds) != 0) { + int outputPipe[2]; + if (pipe(outputPipe) != 0) { + return result; + } + + int execPipe[2]; + if (pipe(execPipe) != 0) { + close(outputPipe[0]); + close(outputPipe[1]); + return result; + } + + // A close-on-exec pipe reports whether execvp() took over: the parent reads + // EOF only when the program really started, so a missing binary is no longer + // reported as exit code 127 from a successfully started command. + if (fcntl(execPipe[1], F_SETFD, FD_CLOEXEC) != 0) { + close(outputPipe[0]); + close(outputPipe[1]); + close(execPipe[0]); + close(execPipe[1]); return result; } const pid_t pid = fork(); if (pid < 0) { - close(pipeFds[0]); - close(pipeFds[1]); + close(outputPipe[0]); + close(outputPipe[1]); + close(execPipe[0]); + close(execPipe[1]); return result; } if (pid == 0) { - close(pipeFds[0]); - dup2(pipeFds[1], STDOUT_FILENO); - dup2(pipeFds[1], STDERR_FILENO); - close(pipeFds[1]); + close(outputPipe[0]); + close(execPipe[0]); + dup2(outputPipe[1], STDOUT_FILENO); + dup2(outputPipe[1], STDERR_FILENO); + close(outputPipe[1]); std::vector argv; argv.reserve(arguments.size() + 1); @@ -42,23 +66,38 @@ CommandResult runCommand(const std::vector& arguments) { argv.push_back(nullptr); execvp(argv[0], argv.data()); + + const int failure = errno; + // Short write to a fresh pipe cannot block; the value is only a hint. + ssize_t written = write(execPipe[1], &failure, sizeof(failure)); + (void)written; _exit(127); } - close(pipeFds[1]); + close(outputPipe[1]); + close(execPipe[1]); + + int execFailure = 0; + const ssize_t execRead = read(execPipe[0], &execFailure, sizeof(execFailure)); + close(execPipe[0]); + char buffer[4096]; ssize_t count = 0; - while ((count = read(pipeFds[0], buffer, sizeof(buffer))) > 0) { + while ((count = read(outputPipe[0], buffer, sizeof(buffer))) > 0) { result.output.append(buffer, static_cast(count)); } - close(pipeFds[0]); + close(outputPipe[0]); int status = 0; while (waitpid(pid, &status, 0) < 0 && errno == EINTR) { } - result.started = true; - result.exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -1; + result.started = execRead == 0; + if (result.started) { + result.exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -1; + } else if (execFailure != 0) { + result.output += std::string("execvp: ") + std::strerror(execFailure); + } return result; }