Always #define _GNU_SOURCE to pull in pipe2() declarations
[folly.git] / folly / Subprocess.cpp
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "folly/Subprocess.h"
18
19 #if __linux__
20 #include <sys/prctl.h>
21 #endif
22 #include <fcntl.h>
23 #include <poll.h>
24
25 #ifndef _GNU_SOURCE
26 #define _GNU_SOURCE
27 #endif
28 #include <unistd.h>
29
30 #include <array>
31 #include <algorithm>
32 #include <system_error>
33
34 #include <boost/container/flat_set.hpp>
35 #include <boost/range/adaptors.hpp>
36
37 #include <glog/logging.h>
38
39 #include "folly/Conv.h"
40 #include "folly/Exception.h"
41 #include "folly/FileUtil.h"
42 #include "folly/ScopeGuard.h"
43 #include "folly/String.h"
44 #include "folly/io/Cursor.h"
45
46 extern char** environ;
47
48 constexpr int kExecFailure = 127;
49 constexpr int kChildFailure = 126;
50
51 namespace folly {
52
53 ProcessReturnCode::State ProcessReturnCode::state() const {
54   if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
55   if (rawStatus_ == RV_RUNNING) return RUNNING;
56   if (WIFEXITED(rawStatus_)) return EXITED;
57   if (WIFSIGNALED(rawStatus_)) return KILLED;
58   throw std::runtime_error(to<std::string>(
59       "Invalid ProcessReturnCode: ", rawStatus_));
60 }
61
62 void ProcessReturnCode::enforce(State expected) const {
63   State s = state();
64   if (s != expected) {
65     throw std::logic_error(to<std::string>(
66       "Bad use of ProcessReturnCode; state is ", s, " expected ", expected
67     ));
68   }
69 }
70
71 int ProcessReturnCode::exitStatus() const {
72   enforce(EXITED);
73   return WEXITSTATUS(rawStatus_);
74 }
75
76 int ProcessReturnCode::killSignal() const {
77   enforce(KILLED);
78   return WTERMSIG(rawStatus_);
79 }
80
81 bool ProcessReturnCode::coreDumped() const {
82   enforce(KILLED);
83   return WCOREDUMP(rawStatus_);
84 }
85
86 std::string ProcessReturnCode::str() const {
87   switch (state()) {
88   case NOT_STARTED:
89     return "not started";
90   case RUNNING:
91     return "running";
92   case EXITED:
93     return to<std::string>("exited with status ", exitStatus());
94   case KILLED:
95     return to<std::string>("killed by signal ", killSignal(),
96                            (coreDumped() ? " (core dumped)" : ""));
97   }
98   CHECK(false);  // unreached
99 }
100
101 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
102   : returnCode_(rc),
103     what_(returnCode_.str()) {
104 }
105
106 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
107                                            int errCode,
108                                            int errnoValue)
109   : errnoValue_(errnoValue),
110     what_(to<std::string>(errCode == kExecFailure ?
111                             "failed to execute " :
112                             "error preparing to execute ",
113                           executable, ": ", errnoStr(errnoValue))) {
114 }
115
116 namespace {
117
118 // Copy pointers to the given strings in a format suitable for posix_spawn
119 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
120   std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
121   for (int i = 0; i < s.size(); i++) {
122     d[i] = s[i].c_str();
123   }
124   d[s.size()] = nullptr;
125   return d;
126 }
127
128 // Check a wait() status, throw on non-successful
129 void checkStatus(ProcessReturnCode returnCode) {
130   if (returnCode.state() != ProcessReturnCode::EXITED ||
131       returnCode.exitStatus() != 0) {
132     throw CalledProcessError(returnCode);
133   }
134 }
135
136 }  // namespace
137
138 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
139   if (action == Subprocess::PIPE) {
140     if (fd == 0) {
141       action = Subprocess::PIPE_IN;
142     } else if (fd == 1 || fd == 2) {
143       action = Subprocess::PIPE_OUT;
144     } else {
145       throw std::invalid_argument(
146           to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
147     }
148   }
149   fdActions_[fd] = action;
150   return *this;
151 }
152
153 Subprocess::Subprocess(
154     const std::vector<std::string>& argv,
155     const Options& options,
156     const char* executable,
157     const std::vector<std::string>* env)
158   : pid_(-1),
159     returnCode_(RV_NOT_STARTED) {
160   if (argv.empty()) {
161     throw std::invalid_argument("argv must not be empty");
162   }
163   if (!executable) executable = argv[0].c_str();
164   spawn(cloneStrings(argv), executable, options, env);
165 }
166
167 Subprocess::Subprocess(
168     const std::string& cmd,
169     const Options& options,
170     const std::vector<std::string>* env)
171   : pid_(-1),
172     returnCode_(RV_NOT_STARTED) {
173   if (options.usePath_) {
174     throw std::invalid_argument("usePath() not allowed when running in shell");
175   }
176   const char* shell = getenv("SHELL");
177   if (!shell) {
178     shell = "/bin/sh";
179   }
180
181   std::unique_ptr<const char*[]> argv(new const char*[4]);
182   argv[0] = shell;
183   argv[1] = "-c";
184   argv[2] = cmd.c_str();
185   argv[3] = nullptr;
186   spawn(std::move(argv), shell, options, env);
187 }
188
189 Subprocess::~Subprocess() {
190   CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
191     << "Subprocess destroyed without reaping child";
192   closeAll();
193 }
194
195 namespace {
196 void closeChecked(int fd) {
197   checkUnixError(::close(fd), "close");
198 }
199
200 struct ChildErrorInfo {
201   int errCode;
202   int errnoValue;
203 };
204
205 FOLLY_NORETURN void childError(int errFd, int errCode, int errnoValue);
206 void childError(int errFd, int errCode, int errnoValue) {
207   ChildErrorInfo info = {errCode, errnoValue};
208   // Write the error information over the pipe to our parent process.
209   // We can't really do anything else if this write call fails.
210   writeNoInt(errFd, &info, sizeof(info));
211   // exit
212   _exit(errCode);
213 }
214
215 }  // namespace
216
217 void Subprocess::closeAll() {
218   for (auto& p : pipes_) {
219     closeChecked(p.parentFd);
220   }
221   pipes_.clear();
222 }
223
224 void Subprocess::setAllNonBlocking() {
225   for (auto& p : pipes_) {
226     int fd = p.parentFd;
227     int flags = ::fcntl(fd, F_GETFL);
228     checkUnixError(flags, "fcntl");
229     int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
230     checkUnixError(r, "fcntl");
231   }
232 }
233
234 void Subprocess::spawn(
235     std::unique_ptr<const char*[]> argv,
236     const char* executable,
237     const Options& optionsIn,
238     const std::vector<std::string>* env) {
239   if (optionsIn.usePath_ && env) {
240     throw std::invalid_argument(
241         "usePath() not allowed when overriding environment");
242   }
243
244   // Make a copy, we'll mutate options
245   Options options(optionsIn);
246
247   // On error, close all of the pipes_
248   auto pipesGuard = makeGuard([&] {
249     for (auto& p : this->pipes_) {
250       CHECK_ERR(::close(p.parentFd));
251     }
252   });
253
254   // Create a pipe to use to receive error information from the child,
255   // in case it fails before calling exec(), setting the close-on-exec flag
256   // on both sides of the pipe.
257   // This way the pipe will be closed automatically in the child if execve()
258   // succeeds.  If the exec fails the child can write error information to the
259   // pipe.
260   // Note that O_CLOEXEC must be set in a single call while we are creating
261   // the pipe instead of doing pipe()/fcntl separately, which might race if a
262   // another thread calls fork()/exec() concurrently and both sides of the pipe
263   // may be inherited by the corresponding child process without being closed.
264   int errFds[2];
265   int r = ::pipe2(errFds, O_CLOEXEC);
266   checkUnixError(r, "pipe2");
267   SCOPE_EXIT {
268     CHECK_ERR(::close(errFds[0]));
269     if (errFds[1] >= 0) {
270       CHECK_ERR(::close(errFds[1]));
271     }
272   };
273
274   // Perform the actual work of setting up pipes then forking and
275   // executing the child.
276   spawnInternal(std::move(argv), executable, options, env, errFds[1]);
277
278   // After spawnInternal() returns the child is alive.  We have to be very
279   // careful about throwing after this point.  We are inside the constructor,
280   // so if we throw the Subprocess object will have never existed, and the
281   // destructor will never be called.
282   //
283   // We should only throw if we got an error via the errFd, and we know the
284   // child has exited and can be immediately waited for.  In all other cases,
285   // we have no way of cleaning up the child.
286
287   // Close writable side of the errFd pipe in the parent process
288   CHECK_ERR(::close(errFds[1]));
289   errFds[1] = -1;
290
291   // Read from the errFd pipe, to tell if the child ran into any errors before
292   // calling exec()
293   readChildErrorPipe(errFds[0], executable);
294
295   // We have fully succeeded now, so release the guard on pipes_
296   pipesGuard.dismiss();
297 }
298
299 void Subprocess::spawnInternal(
300     std::unique_ptr<const char*[]> argv,
301     const char* executable,
302     Options& options,
303     const std::vector<std::string>* env,
304     int errFd) {
305   // Parent work, pre-fork: create pipes
306   std::vector<int> childFds;
307   // Close all of the childFds as we leave this scope
308   SCOPE_EXIT {
309     // These are only pipes, closing them shouldn't fail
310     for (int cfd : childFds) {
311       CHECK_ERR(::close(cfd));
312     }
313   };
314
315   int r;
316   for (auto& p : options.fdActions_) {
317     if (p.second == PIPE_IN || p.second == PIPE_OUT) {
318       int fds[2];
319       // Set O_CLOEXEC on both ends of the pipe atomically while creating
320       // the pipe. The child will clear O_CLOEXEC on its side of the pipe
321       // before calling exec() so that stays open afterwards.
322       // This way even if a concurrently constructed Subprocess inherits
323       // both ends of this pipe, they will be automatically closed
324       // after the corresponding exec().
325       r = ::pipe2(fds, O_CLOEXEC);
326       checkUnixError(r, "pipe2");
327       PipeInfo pinfo;
328       pinfo.direction = p.second;
329       int cfd;
330       if (p.second == PIPE_IN) {
331         // Child gets reading end
332         pinfo.parentFd = fds[1];
333         cfd = fds[0];
334       } else {
335         pinfo.parentFd = fds[0];
336         cfd = fds[1];
337       }
338       p.second = cfd;  // ensure it gets dup2()ed
339       pinfo.childFd = p.first;
340       childFds.push_back(cfd);
341       pipes_.push_back(pinfo);
342     }
343   }
344
345   // This should already be sorted, as options.fdActions_ is
346   DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
347
348   // Note that the const casts below are legit, per
349   // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
350
351   char** argVec = const_cast<char**>(argv.get());
352
353   // Set up environment
354   std::unique_ptr<const char*[]> envHolder;
355   char** envVec;
356   if (env) {
357     envHolder = cloneStrings(*env);
358     envVec = const_cast<char**>(envHolder.get());
359   } else {
360     envVec = environ;
361   }
362
363   // Block all signals around vfork; see http://ewontfix.com/7/.
364   //
365   // As the child may run in the same address space as the parent until
366   // the actual execve() system call, any (custom) signal handlers that
367   // the parent has might alter parent's memory if invoked in the child,
368   // with undefined results.  So we block all signals in the parent before
369   // vfork(), which will cause them to be blocked in the child as well (we
370   // rely on the fact that Linux, just like all sane implementations, only
371   // clones the calling thread).  Then, in the child, we reset all signals
372   // to their default dispositions (while still blocked), and unblock them
373   // (so the exec()ed process inherits the parent's signal mask)
374   //
375   // The parent also unblocks all signals as soon as vfork() returns.
376   sigset_t allBlocked;
377   r = sigfillset(&allBlocked);
378   checkUnixError(r, "sigfillset");
379   sigset_t oldSignals;
380
381   r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
382   checkPosixError(r, "pthread_sigmask");
383   SCOPE_EXIT {
384     // Restore signal mask
385     r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
386     CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r);  // shouldn't fail
387   };
388
389   pid_t pid = vfork();
390   if (pid == 0) {
391     int errnoValue = prepareChild(options, &oldSignals);
392     if (errnoValue != 0) {
393       childError(errFd, kChildFailure, errnoValue);
394     }
395
396     errnoValue = runChild(executable, argVec, envVec, options);
397     // If we get here, exec() failed.
398     childError(errFd, kExecFailure, errnoValue);
399   }
400   // In parent.  Make sure vfork() succeeded.
401   checkUnixError(pid, errno, "vfork");
402
403   // Child is alive.  We have to be very careful about throwing after this
404   // point.  We are inside the constructor, so if we throw the Subprocess
405   // object will have never existed, and the destructor will never be called.
406   //
407   // We should only throw if we got an error via the errFd, and we know the
408   // child has exited and can be immediately waited for.  In all other cases,
409   // we have no way of cleaning up the child.
410   pid_ = pid;
411   returnCode_ = ProcessReturnCode(RV_RUNNING);
412 }
413
414 int Subprocess::prepareChild(const Options& options,
415                              const sigset_t* sigmask) const {
416   // While all signals are blocked, we must reset their
417   // dispositions to default.
418   for (int sig = 1; sig < NSIG; ++sig) {
419     ::signal(sig, SIG_DFL);
420   }
421   // Unblock signals; restore signal mask.
422   int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
423   if (r != 0) {
424     return r;  // pthread_sigmask() returns an errno value
425   }
426
427   // Change the working directory, if one is given
428   if (!options.childDir_.empty()) {
429     r = ::chdir(options.childDir_.c_str());
430     if (r == -1) {
431       return errno;
432     }
433   }
434
435   for (auto& p : pipes_) {
436     // Clear FD_CLOEXEC on the child side of the pipe so
437     // it stays open after exec() (so that the child could
438     // access it).
439     // See spawnInternal() for why FD_CLOEXEC must be set
440     // by default on pipes.
441     r = fcntl(p.childFd, F_SETFD, 0);
442     if (r == -1) {
443       return errno;
444     }
445   }
446
447   // Close all fds that we're supposed to close.
448   // Note that we're ignoring errors here, in case some of these
449   // fds were set to close on exec.
450   for (auto& p : options.fdActions_) {
451     if (p.second == CLOSE) {
452       ::close(p.first);
453     } else {
454       r = ::dup2(p.second, p.first);
455       if (r == -1) {
456         return errno;
457       }
458     }
459   }
460
461   // If requested, close all other file descriptors.  Don't close
462   // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
463   // Ignore errors.
464   if (options.closeOtherFds_) {
465     for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
466       if (options.fdActions_.count(fd) == 0) {
467         ::close(fd);
468       }
469     }
470   }
471
472 #if __linux__
473   // Opt to receive signal on parent death, if requested
474   if (options.parentDeathSignal_ != 0) {
475     r = prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0);
476     if (r == -1) {
477       return errno;
478     }
479   }
480 #endif
481
482   return 0;
483 }
484
485 int Subprocess::runChild(const char* executable,
486                          char** argv, char** env,
487                          const Options& options) const {
488   // Now, finally, exec.
489   int r;
490   if (options.usePath_) {
491     ::execvp(executable, argv);
492   } else {
493     ::execve(executable, argv, env);
494   }
495   return errno;
496 }
497
498 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
499   ChildErrorInfo info;
500   auto rc = readNoInt(pfd, &info, sizeof(info));
501   if (rc == 0) {
502     // No data means the child executed successfully, and the pipe
503     // was closed due to the close-on-exec flag being set.
504     return;
505   } else if (rc != sizeof(ChildErrorInfo)) {
506     // An error occurred trying to read from the pipe, or we got a partial read.
507     // Neither of these cases should really occur in practice.
508     //
509     // We can't get any error data from the child in this case, and we don't
510     // know if it is successfully running or not.  All we can do is to return
511     // normally, as if the child executed successfully.  If something bad
512     // happened the caller should at least get a non-normal exit status from
513     // the child.
514     LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
515       "rc=" << rc << ", errno=" << errno;
516     return;
517   }
518
519   // We got error data from the child.  The child should exit immediately in
520   // this case, so wait on it to clean up.
521   wait();
522
523   // Throw to signal the error
524   throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
525 }
526
527 ProcessReturnCode Subprocess::poll() {
528   returnCode_.enforce(ProcessReturnCode::RUNNING);
529   DCHECK_GT(pid_, 0);
530   int status;
531   pid_t found = ::waitpid(pid_, &status, WNOHANG);
532   checkUnixError(found, "waitpid");
533   if (found != 0) {
534     returnCode_ = ProcessReturnCode(status);
535     pid_ = -1;
536   }
537   return returnCode_;
538 }
539
540 bool Subprocess::pollChecked() {
541   if (poll().state() == ProcessReturnCode::RUNNING) {
542     return false;
543   }
544   checkStatus(returnCode_);
545   return true;
546 }
547
548 ProcessReturnCode Subprocess::wait() {
549   returnCode_.enforce(ProcessReturnCode::RUNNING);
550   DCHECK_GT(pid_, 0);
551   int status;
552   pid_t found;
553   do {
554     found = ::waitpid(pid_, &status, 0);
555   } while (found == -1 && errno == EINTR);
556   checkUnixError(found, "waitpid");
557   DCHECK_EQ(found, pid_);
558   returnCode_ = ProcessReturnCode(status);
559   pid_ = -1;
560   return returnCode_;
561 }
562
563 void Subprocess::waitChecked() {
564   wait();
565   checkStatus(returnCode_);
566 }
567
568 void Subprocess::sendSignal(int signal) {
569   returnCode_.enforce(ProcessReturnCode::RUNNING);
570   int r = ::kill(pid_, signal);
571   checkUnixError(r, "kill");
572 }
573
574 pid_t Subprocess::pid() const {
575   return pid_;
576 }
577
578 namespace {
579
580 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
581   auto* p = queue.front();
582   if (!p) return std::make_pair(nullptr, 0);
583   return io::Cursor(p).peek();
584 }
585
586 // fd write
587 bool handleWrite(int fd, IOBufQueue& queue) {
588   for (;;) {
589     auto p = queueFront(queue);
590     if (p.second == 0) {
591       return true;  // EOF
592     }
593
594     ssize_t n = writeNoInt(fd, p.first, p.second);
595     if (n == -1 && errno == EAGAIN) {
596       return false;
597     }
598     checkUnixError(n, "write");
599     queue.trimStart(n);
600   }
601 }
602
603 // fd read
604 bool handleRead(int fd, IOBufQueue& queue) {
605   for (;;) {
606     auto p = queue.preallocate(100, 65000);
607     ssize_t n = readNoInt(fd, p.first, p.second);
608     if (n == -1 && errno == EAGAIN) {
609       return false;
610     }
611     checkUnixError(n, "read");
612     if (n == 0) {
613       return true;
614     }
615     queue.postallocate(n);
616   }
617 }
618
619 bool discardRead(int fd) {
620   static const size_t bufSize = 65000;
621   // Thread unsafe, but it doesn't matter.
622   static std::unique_ptr<char[]> buf(new char[bufSize]);
623
624   for (;;) {
625     ssize_t n = readNoInt(fd, buf.get(), bufSize);
626     if (n == -1 && errno == EAGAIN) {
627       return false;
628     }
629     checkUnixError(n, "read");
630     if (n == 0) {
631       return true;
632     }
633   }
634 }
635
636 }  // namespace
637
638 std::pair<std::string, std::string> Subprocess::communicate(
639     StringPiece input) {
640   IOBufQueue inputQueue;
641   inputQueue.wrapBuffer(input.data(), input.size());
642
643   auto outQueues = communicateIOBuf(std::move(inputQueue));
644   auto outBufs = std::make_pair(outQueues.first.move(),
645                                 outQueues.second.move());
646   std::pair<std::string, std::string> out;
647   if (outBufs.first) {
648     outBufs.first->coalesce();
649     out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
650                      outBufs.first->length());
651   }
652   if (outBufs.second) {
653     outBufs.second->coalesce();
654     out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
655                      outBufs.second->length());
656   }
657   return out;
658 }
659
660 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
661     IOBufQueue input) {
662   // If the user supplied a non-empty input buffer, make sure
663   // that stdin is a pipe so we can write the data.
664   if (!input.empty()) {
665     // findByChildFd() will throw std::invalid_argument if no pipe for
666     // STDIN_FILENO exists
667     findByChildFd(STDIN_FILENO);
668   }
669
670   std::pair<IOBufQueue, IOBufQueue> out;
671
672   auto readCallback = [&] (int pfd, int cfd) -> bool {
673     if (cfd == STDOUT_FILENO) {
674       return handleRead(pfd, out.first);
675     } else if (cfd == STDERR_FILENO) {
676       return handleRead(pfd, out.second);
677     } else {
678       // Don't close the file descriptor, the child might not like SIGPIPE,
679       // just read and throw the data away.
680       return discardRead(pfd);
681     }
682   };
683
684   auto writeCallback = [&] (int pfd, int cfd) -> bool {
685     if (cfd == STDIN_FILENO) {
686       return handleWrite(pfd, input);
687     } else {
688       // If we don't want to write to this fd, just close it.
689       return true;
690     }
691   };
692
693   communicate(std::move(readCallback), std::move(writeCallback));
694
695   return out;
696 }
697
698 void Subprocess::communicate(FdCallback readCallback,
699                              FdCallback writeCallback) {
700   returnCode_.enforce(ProcessReturnCode::RUNNING);
701   setAllNonBlocking();
702
703   std::vector<pollfd> fds;
704   fds.reserve(pipes_.size());
705   std::vector<int> toClose;
706   toClose.reserve(pipes_.size());
707
708   while (!pipes_.empty()) {
709     fds.clear();
710     toClose.clear();
711
712     for (auto& p : pipes_) {
713       pollfd pfd;
714       pfd.fd = p.parentFd;
715       // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
716       // child's point of view.
717       if (!p.enabled) {
718         // Still keeping fd in watched set so we get notified of POLLHUP /
719         // POLLERR
720         pfd.events = 0;
721       } else if (p.direction == PIPE_IN) {
722         pfd.events = POLLOUT;
723       } else {
724         pfd.events = POLLIN;
725       }
726       fds.push_back(pfd);
727     }
728
729     int r;
730     do {
731       r = ::poll(fds.data(), fds.size(), -1);
732     } while (r == -1 && errno == EINTR);
733     checkUnixError(r, "poll");
734
735     for (int i = 0; i < pipes_.size(); ++i) {
736       auto& p = pipes_[i];
737       DCHECK_EQ(fds[i].fd, p.parentFd);
738       short events = fds[i].revents;
739
740       bool closed = false;
741       if (events & POLLOUT) {
742         DCHECK(!(events & POLLIN));
743         if (writeCallback(p.parentFd, p.childFd)) {
744           toClose.push_back(i);
745           closed = true;
746         }
747       }
748
749       // Call read callback on POLLHUP, to give it a chance to read (and act
750       // on) end of file
751       if (events & (POLLIN | POLLHUP)) {
752         DCHECK(!(events & POLLOUT));
753         if (readCallback(p.parentFd, p.childFd)) {
754           toClose.push_back(i);
755           closed = true;
756         }
757       }
758
759       if ((events & (POLLHUP | POLLERR)) && !closed) {
760         toClose.push_back(i);
761         closed = true;
762       }
763     }
764
765     // Close the fds in reverse order so the indexes hold after erase()
766     for (int idx : boost::adaptors::reverse(toClose)) {
767       auto pos = pipes_.begin() + idx;
768       closeChecked(pos->parentFd);
769       pipes_.erase(pos);
770     }
771   }
772 }
773
774 void Subprocess::enableNotifications(int childFd, bool enabled) {
775   pipes_[findByChildFd(childFd)].enabled = enabled;
776 }
777
778 bool Subprocess::notificationsEnabled(int childFd) const {
779   return pipes_[findByChildFd(childFd)].enabled;
780 }
781
782 int Subprocess::findByChildFd(int childFd) const {
783   auto pos = std::lower_bound(
784       pipes_.begin(), pipes_.end(), childFd,
785       [] (const PipeInfo& info, int fd) { return info.childFd < fd; });
786   if (pos == pipes_.end() || pos->childFd != childFd) {
787     throw std::invalid_argument(folly::to<std::string>(
788         "child fd not found ", childFd));
789   }
790   return pos - pipes_.begin();
791 }
792
793 void Subprocess::closeParentFd(int childFd) {
794   int idx = findByChildFd(childFd);
795   closeChecked(pipes_[idx].parentFd);
796   pipes_.erase(pipes_.begin() + idx);
797 }
798
799 namespace {
800
801 class Initializer {
802  public:
803   Initializer() {
804     // We like EPIPE, thanks.
805     ::signal(SIGPIPE, SIG_IGN);
806   }
807 };
808
809 Initializer initializer;
810
811 }  // namespace
812
813 }  // namespace folly
814