Improve waitpid error handling
[folly.git] / folly / Subprocess.h
1 /*
2  * Copyright 2015 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 /**
18  * Subprocess library, modeled after Python's subprocess module
19  * (http://docs.python.org/2/library/subprocess.html)
20  *
21  * This library defines one class (Subprocess) which represents a child
22  * process.  Subprocess has two constructors: one that takes a vector<string>
23  * and executes the given executable without using the shell, and one
24  * that takes a string and executes the given command using the shell.
25  * Subprocess allows you to redirect the child's standard input, standard
26  * output, and standard error to/from child descriptors in the parent,
27  * or to create communication pipes between the child and the parent.
28  *
29  * The simplest example is a thread-safe [1] version of the system() library
30  * function:
31  *    Subprocess(cmd).wait();
32  * which executes the command using the default shell and waits for it
33  * to complete, returning the exit status.
34  *
35  * A thread-safe [1] version of popen() (type="r", to read from the child):
36  *    Subprocess proc(cmd, Subprocess::pipeStdout());
37  *    // read from proc.stdout()
38  *    proc.wait();
39  *
40  * A thread-safe [1] version of popen() (type="w", to write to the child):
41  *    Subprocess proc(cmd, Subprocess::pipeStdin());
42  *    // write to proc.stdin()
43  *    proc.wait();
44  *
45  * If you want to redirect both stdin and stdout to pipes, you can, but note
46  * that you're subject to a variety of deadlocks.  You'll want to use
47  * nonblocking I/O, like the callback version of communicate().
48  *
49  * The string or IOBuf-based variants of communicate() are the simplest way
50  * to communicate with a child via its standard input, standard output, and
51  * standard error.  They buffer everything in memory, so they are not great
52  * for large amounts of data (or long-running processes), but they are much
53  * simpler than the callback version.
54  *
55  * == A note on thread-safety ==
56  *
57  * [1] "thread-safe" refers ONLY to the fact that Subprocess is very careful
58  * to fork in a way that does not cause grief in multithreaded programs.
59  *
60  * Caveat: If your system does not have the atomic pipe2 system call, it is
61  * not safe to concurrently call Subprocess from different threads.
62  * Therefore, it is best to have a single thread be responsible for spawning
63  * subprocesses.
64  *
65  * A particular instances of Subprocess is emphatically **not** thread-safe.
66  * If you need to simultaneously communicate via the pipes, and interact
67  * with the Subprocess state, your best bet is to:
68  *  - takeOwnershipOfPipes() to separate the pipe I/O from the subprocess.
69  *  - Only interact with the Subprocess from one thread at a time.
70  *
71  * The current implementation of communicate() cannot be safely interrupted.
72  * To do so correctly, one would need to use EventFD, or open a dedicated
73  * pipe to be messaged from a different thread -- in particular, kill() will
74  * not do, since a descendant may keep the pipes open indefinitely.
75  *
76  * So, once you call communicate(), you must wait for it to return, and not
77  * touch the pipes from other threads.  closeParentFd() is emphatically
78  * unsafe to call concurrently, and even sendSignal() is not a good idea.
79  * You can perhaps give the Subprocess's PID to a different thread before
80  * starting communicate(), and use that PID to send a signal without
81  * accessing the Subprocess object.  In that case, you will need a mutex
82  * that ensures you don't wait() before you sent said signal.  In a
83  * nutshell, don't do this.
84  *
85  * In fact, signals are inherently concurrency-unsafe on Unix: if you signal
86  * a PID, while another thread is in waitpid(), the signal may fire either
87  * before or after the process is reaped.  This means that your signal can,
88  * in pathological circumstances, be delivered to the wrong process (ouch!).
89  * To avoid this, you should only use non-blocking waits (i.e. poll()), and
90  * make sure to serialize your signals (i.e. kill()) with the waits --
91  * either wait & signal from the same thread, or use a mutex.
92  */
93 #ifndef FOLLY_SUBPROCESS_H_
94 #define FOLLY_SUBPROCESS_H_
95
96 #include <sys/types.h>
97 #include <signal.h>
98 #if __APPLE__
99 #include <sys/wait.h>
100 #else
101 #include <wait.h>
102 #endif
103
104 #include <exception>
105 #include <vector>
106 #include <string>
107
108 #include <boost/container/flat_map.hpp>
109 #include <boost/operators.hpp>
110
111 #include <folly/File.h>
112 #include <folly/FileUtil.h>
113 #include <folly/gen/String.h>
114 #include <folly/io/IOBufQueue.h>
115 #include <folly/MapUtil.h>
116 #include <folly/Portability.h>
117 #include <folly/Range.h>
118
119 namespace folly {
120
121 /**
122  * Class to wrap a process return code.
123  */
124 class Subprocess;
125 class ProcessReturnCode {
126   friend class Subprocess;
127  public:
128   enum State {
129     NOT_STARTED,
130     RUNNING,
131     EXITED,
132     KILLED
133   };
134
135   // Trivially copyable
136   ProcessReturnCode(const ProcessReturnCode& p) = default;
137   ProcessReturnCode& operator=(const ProcessReturnCode& p) = default;
138   // Non-default move: In order for Subprocess to be movable, the "moved
139   // out" state must not be "running", or ~Subprocess() will abort.
140   ProcessReturnCode(ProcessReturnCode&& p) noexcept;
141   ProcessReturnCode& operator=(ProcessReturnCode&& p) noexcept;
142
143   /**
144    * Process state.  One of:
145    * NOT_STARTED: process hasn't been started successfully
146    * RUNNING: process is currently running
147    * EXITED: process exited (successfully or not)
148    * KILLED: process was killed by a signal.
149    */
150   State state() const;
151
152   /**
153    * Helper wrappers around state().
154    */
155   bool notStarted() const { return state() == NOT_STARTED; }
156   bool running() const { return state() == RUNNING; }
157   bool exited() const { return state() == EXITED; }
158   bool killed() const { return state() == KILLED; }
159
160   /**
161    * Exit status.  Only valid if state() == EXITED; throws otherwise.
162    */
163   int exitStatus() const;
164
165   /**
166    * Signal that caused the process's termination.  Only valid if
167    * state() == KILLED; throws otherwise.
168    */
169   int killSignal() const;
170
171   /**
172    * Was a core file generated?  Only valid if state() == KILLED; throws
173    * otherwise.
174    */
175   bool coreDumped() const;
176
177   /**
178    * String representation; one of
179    * "not started"
180    * "running"
181    * "exited with status <status>"
182    * "killed by signal <signal>"
183    * "killed by signal <signal> (core dumped)"
184    */
185   std::string str() const;
186
187   /**
188    * Helper function to enforce a precondition based on this.
189    * Throws std::logic_error if in an unexpected state.
190    */
191   void enforce(State state) const;
192  private:
193   explicit ProcessReturnCode(int rv) : rawStatus_(rv) { }
194   static constexpr int RV_NOT_STARTED = -2;
195   static constexpr int RV_RUNNING = -1;
196
197   int rawStatus_;
198 };
199
200 /**
201  * Base exception thrown by the Subprocess methods.
202  */
203 class SubprocessError : public std::exception {};
204
205 /**
206  * Exception thrown by *Checked methods of Subprocess.
207  */
208 class CalledProcessError : public SubprocessError {
209  public:
210   explicit CalledProcessError(ProcessReturnCode rc);
211   ~CalledProcessError() throw() = default;
212   const char* what() const throw() FOLLY_OVERRIDE { return what_.c_str(); }
213   ProcessReturnCode returnCode() const { return returnCode_; }
214  private:
215   ProcessReturnCode returnCode_;
216   std::string what_;
217 };
218
219 /**
220  * Exception thrown if the subprocess cannot be started.
221  */
222 class SubprocessSpawnError : public SubprocessError {
223  public:
224   SubprocessSpawnError(const char* executable, int errCode, int errnoValue);
225   ~SubprocessSpawnError() throw() = default;
226   const char* what() const throw() FOLLY_OVERRIDE { return what_.c_str(); }
227   int errnoValue() const { return errnoValue_; }
228
229  private:
230   int errnoValue_;
231   std::string what_;
232 };
233
234 /**
235  * Subprocess.
236  */
237 class Subprocess {
238  public:
239   static const int CLOSE = -1;
240   static const int PIPE = -2;
241   static const int PIPE_IN = -3;
242   static const int PIPE_OUT = -4;
243
244   /**
245    * Class representing various options: file descriptor behavior, and
246    * whether to use $PATH for searching for the executable,
247    *
248    * By default, we don't use $PATH, file descriptors are closed if
249    * the close-on-exec flag is set (fcntl FD_CLOEXEC) and inherited
250    * otherwise.
251    */
252   class Options : private boost::orable<Options> {
253     friend class Subprocess;
254    public:
255     Options() {}  // E.g. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58328
256
257     /**
258      * Change action for file descriptor fd.
259      *
260      * "action" may be another file descriptor number (dup2()ed before the
261      * child execs), or one of CLOSE, PIPE_IN, and PIPE_OUT.
262      *
263      * CLOSE: close the file descriptor in the child
264      * PIPE_IN: open a pipe *from* the child
265      * PIPE_OUT: open a pipe *to* the child
266      *
267      * PIPE is a shortcut; same as PIPE_IN for stdin (fd 0), same as
268      * PIPE_OUT for stdout (fd 1) or stderr (fd 2), and an error for
269      * other file descriptors.
270      */
271     Options& fd(int fd, int action);
272
273     /**
274      * Shortcut to change the action for standard input.
275      */
276     Options& stdin(int action) { return fd(STDIN_FILENO, action); }
277
278     /**
279      * Shortcut to change the action for standard output.
280      */
281     Options& stdout(int action) { return fd(STDOUT_FILENO, action); }
282
283     /**
284      * Shortcut to change the action for standard error.
285      * Note that stderr(1) will redirect the standard error to the same
286      * file descriptor as standard output; the equivalent of bash's "2>&1"
287      */
288     Options& stderr(int action) { return fd(STDERR_FILENO, action); }
289
290     Options& pipeStdin() { return fd(STDIN_FILENO, PIPE_IN); }
291     Options& pipeStdout() { return fd(STDOUT_FILENO, PIPE_OUT); }
292     Options& pipeStderr() { return fd(STDERR_FILENO, PIPE_OUT); }
293
294     /**
295      * Close all other fds (other than standard input, output, error,
296      * and file descriptors explicitly specified with fd()).
297      *
298      * This is potentially slow; it's generally a better idea to
299      * set the close-on-exec flag on all file descriptors that shouldn't
300      * be inherited by the child.
301      *
302      * Even with this option set, standard input, output, and error are
303      * not closed; use stdin(CLOSE), stdout(CLOSE), stderr(CLOSE) if you
304      * desire this.
305      */
306     Options& closeOtherFds() { closeOtherFds_ = true; return *this; }
307
308     /**
309      * Use the search path ($PATH) when searching for the executable.
310      */
311     Options& usePath() { usePath_ = true; return *this; }
312
313     /**
314      * Change the child's working directory, after the vfork.
315      */
316     Options& chdir(const std::string& dir) { childDir_ = dir; return *this; }
317
318 #if __linux__
319     /**
320      * Child will receive a signal when the parent exits.
321      */
322     Options& parentDeathSignal(int sig) {
323       parentDeathSignal_ = sig;
324       return *this;
325     }
326 #endif
327
328     /**
329      * Child will be made a process group leader when it starts. Upside: one
330      * can reliably all its kill non-daemonizing descendants.  Downside: the
331      * child will not receive Ctrl-C etc during interactive use.
332      */
333     Options& processGroupLeader() {
334       processGroupLeader_ = true;
335       return *this;
336     }
337
338     /**
339      * Helpful way to combine Options.
340      */
341     Options& operator|=(const Options& other);
342
343    private:
344     typedef boost::container::flat_map<int, int> FdMap;
345     FdMap fdActions_;
346     bool closeOtherFds_{false};
347     bool usePath_{false};
348     std::string childDir_;  // "" keeps the parent's working directory
349 #if __linux__
350     int parentDeathSignal_{0};
351 #endif
352     bool processGroupLeader_{false};
353   };
354
355   static Options pipeStdin() { return Options().stdin(PIPE); }
356   static Options pipeStdout() { return Options().stdout(PIPE); }
357   static Options pipeStderr() { return Options().stderr(PIPE); }
358
359   // Non-copiable, but movable
360   Subprocess(const Subprocess&) = delete;
361   Subprocess& operator=(const Subprocess&) = delete;
362   Subprocess(Subprocess&&) = default;
363   Subprocess& operator=(Subprocess&&) = default;
364
365   /**
366    * Create a subprocess from the given arguments.  argv[0] must be listed.
367    * If not-null, executable must be the actual executable
368    * being used (otherwise it's the same as argv[0]).
369    *
370    * If env is not-null, it must contain name=value strings to be used
371    * as the child's environment; otherwise, we inherit the environment
372    * from the parent.  env must be null if options.usePath is set.
373    */
374   explicit Subprocess(
375       const std::vector<std::string>& argv,
376       const Options& options = Options(),
377       const char* executable = nullptr,
378       const std::vector<std::string>* env = nullptr);
379   ~Subprocess();
380
381   /**
382    * Create a subprocess run as a shell command (as shell -c 'command')
383    *
384    * The shell to use is taken from the environment variable $SHELL,
385    * or /bin/sh if $SHELL is unset.
386    */
387   explicit Subprocess(
388       const std::string& cmd,
389       const Options& options = Options(),
390       const std::vector<std::string>* env = nullptr);
391
392   ////
393   //// The methods below only manipulate the process state, and do not
394   //// affect its communication pipes.
395   ////
396
397   /**
398    * Return the child's pid, or -1 if the child wasn't successfully spawned
399    * or has already been wait()ed upon.
400    */
401   pid_t pid() const;
402
403   /**
404    * Return the child's status (as per wait()) if the process has already
405    * been waited on, -1 if the process is still running, or -2 if the
406    * process hasn't been successfully started.  NOTE that this does not call
407    * waitpid() or Subprocess::poll(), but simply returns the status stored
408    * in the Subprocess object.
409    */
410   ProcessReturnCode returnCode() const { return returnCode_; }
411
412   /**
413    * Poll the child's status and return it. Return the exit status if the
414    * subprocess had quit, or RUNNING otherwise.  Throws an std::logic_error
415    * if called on a Subprocess whose status is no longer RUNNING.  No other
416    * exceptions are possible.  Aborts on egregious violations of contract,
417    * e.g. if you wait for the underlying process without going through this
418    * Subprocess instance.
419    */
420   ProcessReturnCode poll();
421
422   /**
423    * Poll the child's status.  If the process is still running, return false.
424    * Otherwise, return true if the process exited with status 0 (success),
425    * or throw CalledProcessError if the process exited with a non-zero status.
426    */
427   bool pollChecked();
428
429   /**
430    * Wait for the process to terminate and return its status.  Like poll(),
431    * the only exception this can throw is std::logic_error if you call this
432    * on a Subprocess whose status is RUNNING.  Aborts on egregious
433    * violations of contract, like an out-of-band waitpid(p.pid(), 0, 0).
434    */
435   ProcessReturnCode wait();
436
437   /**
438    * Wait for the process to terminate, throw if unsuccessful.
439    */
440   void waitChecked();
441
442   /**
443    * Send a signal to the child.  Shortcuts for the commonly used Unix
444    * signals are below.
445    */
446   void sendSignal(int signal);
447   void terminate() { sendSignal(SIGTERM); }
448   void kill() { sendSignal(SIGKILL); }
449
450   ////
451   //// The methods below only affect the process's communication pipes, but
452   //// not its return code or state (they do not poll() or wait()).
453   ////
454
455   /**
456    * Communicate with the child until all pipes to/from the child are closed.
457    *
458    * The input buffer is written to the process' stdin pipe, and data is read
459    * from the stdout and stderr pipes.  Non-blocking I/O is performed on all
460    * pipes simultaneously to avoid deadlocks.
461    *
462    * The stdin pipe will be closed after the full input buffer has been written.
463    * An error will be thrown if a non-empty input buffer is supplied but stdin
464    * was not configured as a pipe.
465    *
466    * Returns a pair of buffers containing the data read from stdout and stderr.
467    * If stdout or stderr is not a pipe, an empty IOBuf queue will be returned
468    * for the respective buffer.
469    *
470    * Note that communicate() and communicateIOBuf() both return when all
471    * pipes to/from the child are closed; the child might stay alive after
472    * that, so you must still wait().
473    *
474    * communicateIOBuf() uses IOBufQueue for buffering (which has the
475    * advantage that it won't try to allocate all data at once), but it does
476    * store the subprocess's entire output in memory before returning.
477    *
478    * communicate() uses strings for simplicity.
479    */
480   std::pair<IOBufQueue, IOBufQueue> communicateIOBuf(
481       IOBufQueue input = IOBufQueue());
482
483   std::pair<std::string, std::string> communicate(
484       StringPiece input = StringPiece());
485
486   /**
487    * Communicate with the child until all pipes to/from the child are closed.
488    *
489    * == Semantics ==
490    *
491    * readCallback(pfd, cfd) will be called whenever there's data available
492    * on any pipe *from* the child (PIPE_OUT).  pfd is the file descriptor
493    * in the parent (that you use to read from); cfd is the file descriptor
494    * in the child (used for identifying the stream; 1 = child's standard
495    * output, 2 = child's standard error, etc)
496    *
497    * writeCallback(pfd, cfd) will be called whenever a pipe *to* the child is
498    * writable (PIPE_IN).  pfd is the file descriptor in the parent (that you
499    * use to write to); cfd is the file descriptor in the child (used for
500    * identifying the stream; 0 = child's standard input, etc)
501    *
502    * The read and write callbacks must read from / write to pfd and return
503    * false during normal operation.  Return true to tell communicate() to
504    * close the pipe.  For readCallback, this might send SIGPIPE to the
505    * child, or make its writes fail with EPIPE, so you should generally
506    * avoid returning true unless you've reached end-of-file.
507    *
508    * communicate() returns when all pipes to/from the child are closed; the
509    * child might stay alive after that, so you must still wait().
510    * Conversely, the child may quit long before its pipes are closed, since
511    * its descendants can keep them alive forever.
512    *
513    * Most users won't need to use this callback version; the simpler version
514    * of communicate (which buffers data in memory) will probably work fine.
515    *
516    * == Things you must get correct ==
517    *
518    * 1) You MUST consume all data passed to readCallback (or return true to
519    * close the pipe).  Similarly, you MUST write to a writable pipe (or
520    * return true to close the pipe).  To do otherwise is an error that can
521    * result in a deadlock.  You must do this even for pipes you are not
522    * interested in.
523    *
524    * 2) pfd is nonblocking, so be prepared for read() / write() to return -1
525    * and set errno to EAGAIN (in which case you should return false).  Use
526    * readNoInt() from FileUtil.h to handle interrupted reads for you.
527    *
528    * 3) Your callbacks MUST NOT call any of the Subprocess methods that
529    * manipulate the pipe FDs.  Check the docblocks, but, for example,
530    * neither closeParentFd (return true instead) nor takeOwnershipOfPipes
531    * are safe.  Stick to reading/writing from pfd, as appropriate.
532    *
533    * == Good to know ==
534    *
535    * 1) See ReadLinesCallback for an easy way to consume the child's output
536    * streams line-by-line (or tokenized by another delimiter).
537    *
538    * 2) "Wait until the descendants close the pipes" is usually the behavior
539    * you want, since the descendants may have something to say even if the
540    * immediate child is dead.  If you need to be able to force-close all
541    * parent FDs, communicate() will NOT work for you.  Do it your own way by
542    * using takeOwnershipOfPipes().
543    *
544    * Why not? You can return "true" from your callbacks to sever active
545    * pipes, but inactive ones can remain open indefinitely.  It is
546    * impossible to safely close inactive pipes while another thread is
547    * blocked in communicate().  This is BY DESIGN.  Racing communicate()'s
548    * read/write callbacks can result in wrong I/O and data corruption.  This
549    * class would need internal synchronization and timeouts, a poor and
550    * expensive implementation choice, in order to make closeParentFd()
551    * thread-safe.
552    */
553   typedef std::function<bool(int, int)> FdCallback;
554   void communicate(FdCallback readCallback, FdCallback writeCallback);
555
556   /**
557    * A readCallback for Subprocess::communicate() that helps you consume
558    * lines (or other delimited pieces) from your subprocess's file
559    * descriptors.  Use the readLinesCallback() helper to get template
560    * deduction.  For example:
561    *
562    *   auto read_cb = Subprocess::readLinesCallback(
563    *     [](int fd, folly::StringPiece s) {
564    *       std::cout << fd << " said: " << s;
565    *       return false;  // Keep reading from the child
566    *     }
567    *   );
568    *   subprocess.communicate(
569    *     // ReadLinesCallback contains StreamSplitter contains IOBuf, making
570    *     // it noncopyable, whereas std::function must be copyable.  So, we
571    *     // keep the callback in a local, and instead pass a reference.
572    *     std::ref(read_cb),
573    *     [](int pdf, int cfd){ return true; }  // Don't write to the child
574    *   );
575    *
576    * If a file line exceeds maxLineLength, your callback will get some
577    * initial chunks of maxLineLength with no trailing delimiters.  The final
578    * chunk of a line is delimiter-terminated iff the delimiter was present
579    * in the input.  In particular, the last line in a file always lacks a
580    * delimiter -- so if a file ends on a delimiter, the final line is empty.
581    *
582    * Like a regular communicate() callback, your fdLineCb() normally returns
583    * false.  It may return true to tell Subprocess to close the underlying
584    * file descriptor.  The child process may then receive SIGPIPE or get
585    * EPIPE errors on writes.
586    */
587   template <class Callback>
588   class ReadLinesCallback {
589    private:
590     // Binds an FD to the client-provided FD+line callback
591     struct StreamSplitterCallback {
592       StreamSplitterCallback(Callback& cb, int fd) : cb_(cb), fd_(fd) { }
593       // The return value semantics are inverted vs StreamSplitter
594       bool operator()(StringPiece s) { return !cb_(fd_, s); }
595       Callback& cb_;
596       int fd_;
597     };
598     typedef gen::StreamSplitter<StreamSplitterCallback> LineSplitter;
599    public:
600     explicit ReadLinesCallback(
601       Callback&& fdLineCb,
602       uint64_t maxLineLength = 0,  // No line length limit by default
603       char delimiter = '\n',
604       uint64_t bufSize = 1024
605     ) : fdLineCb_(std::move(fdLineCb)),
606         maxLineLength_(maxLineLength),
607         delimiter_(delimiter),
608         bufSize_(bufSize) {}
609
610     bool operator()(int pfd, int cfd) {
611       // Make a splitter for this cfd if it doesn't already exist
612       auto it = fdToSplitter_.find(cfd);
613       auto& splitter = (it != fdToSplitter_.end()) ? it->second
614         : fdToSplitter_.emplace(cfd, LineSplitter(
615             delimiter_, StreamSplitterCallback(fdLineCb_, cfd), maxLineLength_
616           )).first->second;
617       // Read as much as we can from this FD
618       char buf[bufSize_];
619       while (true) {
620         ssize_t ret = readNoInt(pfd, buf, bufSize_);
621         if (ret == -1 && errno == EAGAIN) {  // No more data for now
622           return false;
623         }
624         if (ret == 0) {  // Reached end-of-file
625           splitter.flush();  // Ignore return since the file is over anyway
626           return true;
627         }
628         if (!splitter(StringPiece(buf, ret))) {
629           return true;  // The callback told us to stop
630         }
631       }
632     }
633
634    private:
635     Callback fdLineCb_;
636     const uint64_t maxLineLength_;
637     const char delimiter_;
638     const uint64_t bufSize_;
639     // We lazily make splitters for all cfds that get used.
640     std::unordered_map<int, LineSplitter> fdToSplitter_;
641   };
642
643   // Helper to enable template deduction
644   template <class Callback>
645   static ReadLinesCallback<Callback> readLinesCallback(
646       Callback&& fdLineCb,
647       uint64_t maxLineLength = 0,  // No line length limit by default
648       char delimiter = '\n',
649       uint64_t bufSize = 1024) {
650     return ReadLinesCallback<Callback>(
651       std::move(fdLineCb), maxLineLength, delimiter, bufSize
652     );
653   }
654
655   /**
656    * communicate() callbacks can use this to temporarily enable/disable
657    * notifications (callbacks) for a pipe to/from the child.  By default,
658    * all are enabled.  Useful for "chatty" communication -- you want to
659    * disable write callbacks until you receive the expected message.
660    *
661    * Disabling a pipe does not free you from the requirement to consume all
662    * incoming data.  Failing to do so will easily create deadlock bugs.
663    *
664    * Throws if the childFd is not known.
665    */
666   void enableNotifications(int childFd, bool enabled);
667
668   /**
669    * Are notifications for one pipe to/from child enabled?  Throws if the
670    * childFd is not known.
671    */
672   bool notificationsEnabled(int childFd) const;
673
674   ////
675   //// The following methods are meant for the cases when communicate() is
676   //// not suitable.  You should not need them when you call communicate(),
677   //// and, in fact, it is INHERENTLY UNSAFE to use closeParentFd() or
678   //// takeOwnershipOfPipes() from a communicate() callback.
679   ////
680
681   /**
682    * Close the parent file descriptor given a file descriptor in the child.
683    * DO NOT USE from communicate() callbacks; make them return true instead.
684    */
685   void closeParentFd(int childFd);
686
687   /**
688    * Set all pipes from / to child to be non-blocking.  communicate() does
689    * this for you.
690    */
691   void setAllNonBlocking();
692
693   /**
694    * Get parent file descriptor corresponding to the given file descriptor
695    * in the child.  Throws if childFd isn't a pipe (PIPE_IN / PIPE_OUT).
696    * Do not close() the returned file descriptor; use closeParentFd, above.
697    */
698   int parentFd(int childFd) const {
699     return pipes_[findByChildFd(childFd)].pipe.fd();
700   }
701   int stdin() const { return parentFd(0); }
702   int stdout() const { return parentFd(1); }
703   int stderr() const { return parentFd(2); }
704
705   /**
706    * The child's pipes are logically separate from the process metadata
707    * (they may even be kept alive by the child's descendants).  This call
708    * lets you manage the pipes' lifetime separetely from the lifetime of the
709    * child process.
710    *
711    * After this call, the Subprocess instance will have no knowledge of
712    * these pipes, and the caller assumes responsibility for managing their
713    * lifetimes.  Pro-tip: prefer to explicitly close() the pipes, since
714    * folly::File would otherwise silently suppress I/O errors.
715    *
716    * No, you may NOT call this from a communicate() callback.
717    */
718   struct ChildPipe {
719     ChildPipe(int fd, folly::File&& ppe) : childFd(fd), pipe(std::move(ppe)) {}
720     int childFd;
721     folly::File pipe;  // Owns the parent FD
722   };
723   std::vector<ChildPipe> takeOwnershipOfPipes();
724
725  private:
726   static const int RV_RUNNING = ProcessReturnCode::RV_RUNNING;
727   static const int RV_NOT_STARTED = ProcessReturnCode::RV_NOT_STARTED;
728
729   // spawn() sets up a pipe to read errors from the child,
730   // then calls spawnInternal() to do the bulk of the work.  Once
731   // spawnInternal() returns it reads the error pipe to see if the child
732   // encountered any errors.
733   void spawn(
734       std::unique_ptr<const char*[]> argv,
735       const char* executable,
736       const Options& options,
737       const std::vector<std::string>* env);
738   void spawnInternal(
739       std::unique_ptr<const char*[]> argv,
740       const char* executable,
741       Options& options,
742       const std::vector<std::string>* env,
743       int errFd);
744
745   // Actions to run in child.
746   // Note that this runs after vfork(), so tread lightly.
747   // Returns 0 on success, or an errno value on failure.
748   int prepareChild(const Options& options,
749                    const sigset_t* sigmask,
750                    const char* childDir) const;
751   int runChild(const char* executable, char** argv, char** env,
752                const Options& options) const;
753
754   /**
755    * Read from the error pipe, and throw SubprocessSpawnError if the child
756    * failed before calling exec().
757    */
758   void readChildErrorPipe(int pfd, const char* executable);
759
760   // Returns an index into pipes_. Throws std::invalid_argument if not found.
761   size_t findByChildFd(const int childFd) const;
762
763
764   pid_t pid_;
765   ProcessReturnCode returnCode_;
766
767   /**
768    * Represents a pipe between this process, and the child process (or its
769    * descendant).  To interact with these pipes, you can use communicate(),
770    * or use parentFd() and related methods, or separate them from the
771    * Subprocess instance entirely via takeOwnershipOfPipes().
772    */
773   struct Pipe : private boost::totally_ordered<Pipe> {
774     folly::File pipe; // Our end of the pipe, wrapped in a File to auto-close.
775     int childFd = -1; // Identifies the pipe: what FD is this in the child?
776     int direction = PIPE_IN; // one of PIPE_IN / PIPE_OUT
777     bool enabled = true; // Are notifications enabled in communicate()?
778
779     bool operator<(const Pipe& other) const {
780       return childFd < other.childFd;
781     }
782     bool operator==(const Pipe& other) const {
783       return childFd == other.childFd;
784     }
785   };
786
787   // Populated at process start according to fdActions, empty after
788   // takeOwnershipOfPipes().  Sorted by childFd.  Can only have elements
789   // erased, but not inserted, after being populated.
790   //
791   // The number of pipes between parent and child is assumed to be small,
792   // so we're happy with a vector here, even if it means linear erase.
793   std::vector<Pipe> pipes_;
794 };
795
796 inline Subprocess::Options& Subprocess::Options::operator|=(
797     const Subprocess::Options& other) {
798   if (this == &other) return *this;
799   // Replace
800   for (auto& p : other.fdActions_) {
801     fdActions_[p.first] = p.second;
802   }
803   closeOtherFds_ |= other.closeOtherFds_;
804   usePath_ |= other.usePath_;
805   processGroupLeader_ |= other.processGroupLeader_;
806   return *this;
807 }
808
809 }  // namespace folly
810
811 #endif /* FOLLY_SUBPROCESS_H_ */