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