22 pipe_t(
const char *executable,
const char *
const arguments[],
bool writing) {
23 const long max_fd = sysconf(_SC_OPEN_MAX);
28 if (pipe2(descriptors, O_CLOEXEC) != 0) {
33 for (
int &fd : descriptors) {
35 const int replacement = fcntl(fd, F_DUPFD_CLOEXEC, 3);
36 if (replacement < 0) {
37 close(descriptors[0]);
38 close(descriptors[1]);
48 const int source = descriptors[writing ? 0 : 1];
49 const int target = writing ? STDIN_FILENO : STDOUT_FILENO;
50 if (dup2(source, target) < 0) {
58 if (syscall(SYS_close_range, 3U, ~0U, 0U) != 0)
61 for (
long fd = 3; fd < max_fd; ++fd) {
62 close(
static_cast<int>(fd));
65 execv(executable,
const_cast<char *
const *
>(arguments));
69 close(descriptors[writing ? 0 : 1]);
70 const int parent_fd = descriptors[writing ? 1 : 0];
75 stream = fdopen(parent_fd, writing ?
"w" :
"r");
82 pipe_t(
const pipe_t &) =
delete;
83 pipe_t &operator=(
const pipe_t &) =
delete;
94 const int close_status = stream ? fclose(stream) : 0;
102 result = waitpid(child, &status, 0);
103 }
while (result < 0 && errno == EINTR);
105 return close_status == 0 && result > 0 && WIFEXITED(status) && WEXITSTATUS(status) == 0;
108 bool write(std::string_view content) {
116 sigaddset(&mask, SIGPIPE);
117 sigset_t previous_mask;
118 if (pthread_sigmask(SIG_BLOCK, &mask, &previous_mask) != 0) {
122 const bool had_pending_sigpipe = sigpending(&pending) == 0 && sigismember(&pending, SIGPIPE) == 1;
123 const bool wrote_all = fwrite(content.data(), 1, content.size(), stream) == content.size();
124 const bool closed = finish();
125 if (!had_pending_sigpipe) {
126 const timespec no_wait {};
127 while (sigtimedwait(&mask,
nullptr, &no_wait) < 0 && errno == EINTR) {}
129 pthread_sigmask(SIG_SETMASK, &previous_mask,
nullptr);
130 return wrote_all && closed;
134 FILE *stream =
nullptr;