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