VLink  2.3.0
A high-performance communication middleware
process.h
浏览该文件的文档.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file process.h
26  * @brief Portable child-process driver with asynchronous I/O notifications.
27  *
28  * @details
29  * @c vlink::Process spawns a single child program at a time and exposes a QProcess-style
30  * surface for inspecting its lifecycle, reading captured output, writing to its standard
31  * input, and triggering termination. Output capture, exit notification, and timer-driven
32  * polling all run on an internal monitor thread.
33  *
34  * Capability groups exposed by the class:
35  *
36  * | Group | Representative members |
37  * | --------------------- | ------------------------------------------------------------------------ |
38  * | Lifecycle | @c start, @c start_command, @c terminate, @c kill, @c close |
39  * | Process metadata | @c get_process_id, @c get_state, @c get_error, @c get_exit_code |
40  * | Environment & cwd | @c set_environment, @c set_inherit_environment, @c set_working_directory |
41  * | I/O routing | @c set_process_mode, @c get_process_mode |
42  * | stdout/stderr capture | @c read_line_stdout, @c read_all, @c bytes_available_stdout |
43  * | stdin writing | @c write, @c close_write_channel |
44  * | Async notifications | @c register_finished_callback, @c register_ready_read_stdout_callback |
45  * | Synchronous waits | @c wait_for_started, @c wait_for_finished, @c wait_for_ready_read |
46  * | Static helpers | @c execute, @c start_detached |
47  *
48  * I/O channel routing modes:
49  *
50  * | Mode | stdout | stderr |
51  * | ----------------------- | ------------------- | ------------------- |
52  * | @c kSeparateMode | Buffered pipe | Buffered pipe |
53  * | @c kMergedMode | Buffered pipe | Merged into stdout |
54  * | @c kForwardedMode | Inherits parent | Inherits parent |
55  * | @c kForwardedOutputMode | Inherits parent | Buffered pipe |
56  * | @c kForwardedErrorMode | Buffered pipe | Inherits parent |
57  *
58  * @note
59  * - Callbacks run on the monitor thread or synchronously in the calling operation; protect shared state accordingly.
60  * - The destructor first sends @c SIGTERM, drains pending I/O, then optionally escalates to
61  * @c SIGKILL after @c kDestructorWaitTimeoutMs (5000 ms) before joining.
62  * - The class is non-copyable and non-movable.
63  * - POSIX only: the host must leave @c SIGCHLD at its default disposition. With
64  * @c SIG_IGN, or with an application handler that itself calls @c waitpid(-1, ...), the
65  * child is reaped elsewhere, every internal @c waitpid fails with @c ECHILD, and the loop
66  * never observes the exit -- the finished callback does not fire and the state stays
67  * @c kRunningState.
68  * - Stdin operations (@c write, @c close_write_channel) and @c close are not synchronised
69  * against each other; serialise them in the caller.
70  *
71  * @par Example
72  * @code
73  * vlink::Process proc;
74  * proc.set_process_mode(vlink::Process::kSeparateMode);
75  * proc.register_ready_read_stdout_callback([&proc] {
76  * std::string line;
77  * while (proc.can_read_line_stdout()) {
78  * proc.read_line_stdout(line);
79  * }
80  * });
81  * proc.register_finished_callback([](int code, vlink::Process::ExitStatus status) {
82  * (void)code;
83  * (void)status;
84  * });
85  * proc.start("/usr/bin/ls", {"-la"});
86  * proc.wait_for_finished();
87  * @endcode
88  */
89 
90 #pragma once
91 
92 #include <cstdint>
93 #include <memory>
94 #include <string>
95 #include <unordered_map>
96 #include <vector>
97 
98 #include "./functional.h"
99 #include "./macros.h"
100 
101 namespace vlink {
102 
103 /**
104  * @class Process
105  * @brief Owns and drives a single child process with asynchronous I/O reporting.
106  *
107  * @details
108  * The instance is non-copyable and non-movable. A new child may only be launched after
109  * any previous one has terminated and the internal state has been cleaned up.
110  */
112  public:
113  /**
114  * @enum State
115  * @brief Coarse lifecycle stage of the child process.
116  */
117  enum State : uint8_t {
118  kNotRunningState = 0, ///< No child is currently active.
119  kStartingState = 1, ///< @c start() has been called and the OS is launching the binary.
120  kRunningState = 2, ///< Child has been successfully launched and is executing.
121  };
122 
123  /**
124  * @enum ExitStatus
125  * @brief How the most recent child exited.
126  */
127  enum ExitStatus : uint8_t {
128  kNormalExitStatus = 0, ///< Child returned from @c main or called @c exit normally.
129  kCrashExitStatus = 1, ///< Child was terminated by a signal or crashed.
130  };
131 
132  /**
133  * @enum Error
134  * @brief Last error recorded by a failing operation.
135  *
136  * @details
137  * Each failure overwrites the previous value; the code is not sticky. It is reset to
138  * @c kNoError by @c start(). @c kCrashedError and @c kUnknownError are never produced by
139  * this class -- a crash is reported through @c get_exit_status() instead.
140  */
141  enum Error : uint8_t {
142  kNoError = 0, ///< No error has been observed.
143  kUnknownError = 1, ///< Catch-all bucket for unmapped errors.
144  kStartError = 2, ///< Failed to launch the requested program.
145  kCrashedError = 3, ///< Child process crashed.
146  kTimedOutError = 4, ///< A blocking wait expired before its condition was met.
147  kWriteError = 5, ///< Writing to the child's stdin failed.
148  kReadError = 6, ///< Reading from a captured pipe failed.
149  kBufferOverflowError = 7, ///< Captured output exceeded @c set_max_buffer_size.
150  };
151 
152  /**
153  * @enum Mode
154  * @brief Routing of the child's stdout/stderr file descriptors.
155  */
156  enum Mode : uint8_t {
157  kSeparateMode = 0, ///< Capture stdout and stderr through independent pipes.
158  kMergedMode = 1, ///< Capture stdout; merge stderr into the stdout pipe.
159  kForwardedMode = 2, ///< Inherit parent stdout/stderr without capture.
160  kForwardedOutputMode = 3, ///< Inherit stdout; capture stderr.
161  kForwardedErrorMode = 4, ///< Capture stdout; inherit stderr.
162  };
163 
164  /**
165  * @brief Map type used to pass environment overrides to @c set_environment().
166  */
167  using EnvironmentMap = std::unordered_map<std::string, std::string>;
168 
169  /**
170  * @brief Callback signature invoked on the first error of a run.
171  *
172  * @details
173  * Fires at most once per run; @c start() and @c close() re-arm it. Later errors in the same
174  * run still update @c get_error() but do not re-notify.
175  */
176  using ErrorCallback = Function<void(Error)>;
177 
178  /**
179  * @brief Callback signature invoked when the child exits.
180  *
181  * @details
182  * The first parameter is the exit code; the second is @c kNormalExitStatus or
183  * @c kCrashExitStatus.
184  */
185  using FinishedCallback = Function<void(int, ExitStatus)>;
186 
187  /**
188  * @brief Callback signature invoked whenever new data is available on a pipe.
189  */
190  using ReadyReadCallback = Function<void()>;
191 
192  /**
193  * @brief Callback signature invoked when the process @c State transitions.
194  */
196 
197  /**
198  * @brief Sentinel value used to request an unbounded wait.
199  */
200  static constexpr int kInfinite{-1};
201 
202  /**
203  * @brief Default deadline for @c wait_for_started / @c wait_for_finished (3000 ms).
204  */
205  static constexpr int kDefaultWaitTimeoutMs{3000};
206 
207  /**
208  * @brief Default deadline for blocking writes to the child's stdin (5000 ms).
209  */
210  static constexpr int kDefaultWriteTimeoutMs{5000};
211 
212  /**
213  * @brief Default deadline for the synchronous @c execute() helper (30000 ms).
214  */
215  static constexpr int kDefaultExecuteTimeoutMs{30000};
216 
217  /**
218  * @brief Grace period the destructor allows after sending @c SIGTERM before escalating.
219  */
220  static constexpr int kDestructorWaitTimeoutMs{5000};
221 
222  /**
223  * @brief Constructs an idle process driver with no child attached.
224  */
226 
227  /**
228  * @brief Destructor. Terminates the child if still alive then frees driver resources.
229  *
230  * @details
231  * The sequence sends @c SIGTERM via @c terminate(), drains any pending pipe data,
232  * waits up to @c kDestructorWaitTimeoutMs for a graceful exit, then escalates to
233  * @c SIGKILL via @c kill() and waits up to a further 1000 ms before releasing
234  * the I/O thread, pipes and child handles.
235  */
237 
238  Process(Process&& other) noexcept = delete;
239 
240  Process& operator=(Process&& other) noexcept = delete;
241 
242  /**
243  * @brief Returns the lifecycle state of the currently attached child.
244  *
245  * @return Current @c State value.
246  */
247  [[nodiscard]] State get_state() const;
248 
249  /**
250  * @brief Returns the most recently latched error code.
251  *
252  * @return Sticky @c Error value; @c kNoError if no error has occurred.
253  */
254  [[nodiscard]] Error get_error() const;
255 
256  /**
257  * @brief Returns the exit code of the most recent child process.
258  *
259  * @details
260  * Only meaningful once @c get_state() reports @c kNotRunningState.
261  *
262  * @return Exit code passed to @c exit() or implied by signal termination.
263  */
264  [[nodiscard]] int get_exit_code() const;
265 
266  /**
267  * @brief Returns how the most recent child terminated.
268  *
269  * @return @c kNormalExitStatus on graceful exit, @c kCrashExitStatus on signal/crash.
270  */
271  [[nodiscard]] ExitStatus get_exit_status() const;
272 
273  /**
274  * @brief Reports whether the attached child is currently running.
275  *
276  * @return @c true when @c get_state() equals @c kRunningState.
277  */
278  [[nodiscard]] bool is_running() const;
279 
280  /**
281  * @brief Returns the OS-level identifier of the child process.
282  *
283  * @return Process ID, or @c -1 when no child is attached.
284  */
285  [[nodiscard]] int64_t get_process_id() const;
286 
287  /**
288  * @brief Limits the in-memory capture buffer used for stdout/stderr.
289  *
290  * @details
291  * When the captured output exceeds @p size bytes the @c kBufferOverflowError code is
292  * latched. Passing @c 0 restores the default of 16 MiB.
293  *
294  * @param size New buffer limit in bytes.
295  */
296  void set_max_buffer_size(size_t size);
297 
298  /**
299  * @brief Returns the configured capture-buffer limit.
300  *
301  * @return Buffer size in bytes; default is 16 MiB.
302  */
303  [[nodiscard]] size_t get_max_buffer_size() const;
304 
305  /**
306  * @brief Defines the environment that will be applied at the next @c start() call.
307  *
308  * @param env_map Variable map to merge into or replace the parent environment based on
309  * the @c set_inherit_environment() setting.
310  */
311  void set_environment(const EnvironmentMap& env_map);
312 
313  /**
314  * @brief Returns the currently configured environment override.
315  *
316  * @return Environment variable map.
317  */
318  [[nodiscard]] EnvironmentMap get_environment() const;
319 
320  /**
321  * @brief Sets the I/O channel routing that will be applied at the next @c start() call.
322  *
323  * @param mode Routing mode for stdout/stderr.
324  */
325  void set_process_mode(Mode mode);
326 
327  /**
328  * @brief Returns the currently configured I/O routing mode.
329  *
330  * @return Current @c Mode.
331  */
332  [[nodiscard]] Mode get_process_mode() const;
333 
334  /**
335  * @brief Controls whether the child inherits the parent environment in addition to the override map.
336  *
337  * @param inherit @c true to merge with the parent environment, @c false to use only the override map.
338  */
339  void set_inherit_environment(bool inherit);
340 
341  /**
342  * @brief Reports whether the child currently inherits the parent environment.
343  *
344  * @return @c true when the parent environment is merged.
345  */
346  [[nodiscard]] bool get_inherit_environment() const;
347 
348  /**
349  * @brief Sets the working directory used at the next @c start() call.
350  *
351  * @param dir Absolute path the child should @c chdir to before executing the program.
352  */
353  void set_working_directory(const std::string& dir);
354 
355  /**
356  * @brief Returns the currently configured working directory.
357  *
358  * @return Working directory path.
359  */
360  [[nodiscard]] std::string get_working_directory() const;
361 
362  /**
363  * @brief Installs a callback fired when the @c Error state changes.
364  *
365  * @param callback Callback invoked on the monitor thread or by the calling operation.
366  */
368 
369  /**
370  * @brief Installs a callback fired when the child exits.
371  *
372  * @param callback Callback invoked with exit code and exit status.
373  */
375 
376  /**
377  * @brief Installs a callback fired when stdout has new data buffered.
378  *
379  * @param callback Callback invoked on the monitor thread or by the calling operation.
380  */
382 
383  /**
384  * @brief Installs a callback fired when stderr has new data buffered.
385  *
386  * @param callback Callback invoked on the monitor thread or by the calling operation.
387  */
389 
390  /**
391  * @brief Installs a callback fired on every @c State transition.
392  *
393  * @param callback Callback invoked on the monitor thread or by the calling operation with the new @c State.
394  */
396 
397  /**
398  * @brief Launches @p program with the given argument vector.
399  *
400  * @details
401  * Returns once the launch attempt has either succeeded (state becomes @c kRunningState)
402  * or failed (an @c Error is latched). I/O monitoring continues asynchronously on the
403  * internal monitor thread.
404  *
405  * @param program Path to the executable.
406  * @param arguments Argument vector excluding @c argv[0].
407  */
408  void start(const std::string& program, const std::vector<std::string>& arguments = {});
409 
410  /**
411  * @brief Parses a shell-style command line and launches it.
412  *
413  * @details
414  * Splits @p command on whitespace with quote and backslash handling, preserves quoted
415  * empty arguments, then delegates to @c start().
416  *
417  * @param command Shell-style command string.
418  */
419  void start_command(const std::string& command);
420 
421  /**
422  * @brief Blocks until the child leaves @c kStartingState or the timeout elapses.
423  *
424  * @details A child that already exited still counts as started.
425  *
426  * @param msecs Maximum wait in milliseconds. Default: @c kDefaultWaitTimeoutMs.
427  * @return @c true if the child started (even if since exited); @c false on launch
428  * failure, timeout, or if never started.
429  */
430  bool wait_for_started(int msecs = kDefaultWaitTimeoutMs);
431 
432  /**
433  * @brief Blocks until the child terminates or the timeout elapses.
434  *
435  * @param msecs Maximum wait in milliseconds. Default: @c kDefaultWaitTimeoutMs.
436  * @return @c true when the child has exited within the timeout.
437  */
438  bool wait_for_finished(int msecs = kDefaultWaitTimeoutMs);
439 
440  /**
441  * @brief Blocks until new pipe data becomes available or the timeout elapses.
442  *
443  * @param msecs Maximum wait in milliseconds. Default: @c kDefaultWaitTimeoutMs.
444  * @return @c true when data is now available on stdout or stderr.
445  */
446  bool wait_for_ready_read(int msecs = kDefaultWaitTimeoutMs);
447 
448  /**
449  * @brief Requests cooperative termination of the child.
450  *
451  * @details
452  * POSIX sends @c SIGTERM, which the child may catch. Windows uses @c TerminateProcess,
453  * which is unconditional. @c kill() must be used for a forced exit on POSIX.
454  */
455  void terminate();
456 
457  /**
458  * @brief Forces immediate termination of the child via @c SIGKILL / @c TerminateProcess.
459  */
460  void kill();
461 
462  /**
463  * @brief Sends @c SIGTERM and optionally escalates to @c kill() after the wait timeout.
464  *
465  * @param force_kill_on_timeout When @c true and the child has not exited within
466  * @c kDefaultWaitTimeoutMs, @c kill() is invoked. On
467  * Windows @c terminate() is already forceful so the flag
468  * is effectively ignored. Default: @c false.
469  */
470  void close(bool force_kill_on_timeout = false);
471 
472  /**
473  * @brief Returns the number of buffered bytes available to read from stdout.
474  *
475  * @return Bytes available on stdout.
476  */
477  [[nodiscard]] size_t bytes_available_stdout() const;
478 
479  /**
480  * @brief Returns the number of buffered bytes available to read from stderr.
481  *
482  * @return Bytes available on stderr.
483  */
484  [[nodiscard]] size_t bytes_available_stderr() const;
485 
486  /**
487  * @brief Reports whether a newline-terminated line is fully buffered on stdout.
488  *
489  * @return @c true when @c read_line_stdout() will deliver a complete line.
490  */
491  [[nodiscard]] bool can_read_line_stdout() const;
492 
493  /**
494  * @brief Reports whether a newline-terminated line is fully buffered on stderr.
495  *
496  * @return @c true when @c read_line_stderr() will deliver a complete line.
497  */
498  [[nodiscard]] bool can_read_line_stderr() const;
499 
500  /**
501  * @brief Reads one buffered line from stdout.
502  *
503  * @param line Destination string; receives buffered data including a trailing newline
504  * when one was buffered.
505  * @return @c true when at least one byte was copied into @p line.
506  */
507  bool read_line_stdout(std::string& line);
508 
509  /**
510  * @brief Reads one buffered line from stderr.
511  *
512  * @param line Destination string; receives buffered data including a trailing newline
513  * when one was buffered.
514  * @return @c true when at least one byte was copied into @p line.
515  */
516  bool read_line_stderr(std::string& line);
517 
518  /**
519  * @brief Reads up to @p max_size bytes of buffered stdout into @p buffer.
520  *
521  * @param buffer Destination byte vector.
522  * @param max_size Upper bound on bytes to copy.
523  * @return Number of bytes actually copied.
524  */
525  size_t read_stdout(std::vector<uint8_t>& buffer, size_t max_size);
526 
527  /**
528  * @brief Reads up to @p max_size bytes of buffered stderr into @p buffer.
529  *
530  * @param buffer Destination byte vector.
531  * @param max_size Upper bound on bytes to copy.
532  * @return Number of bytes actually copied.
533  */
534  size_t read_stderr(std::vector<uint8_t>& buffer, size_t max_size);
535 
536  /**
537  * @brief Drains all buffered stdout into @p buffer.
538  *
539  * @param buffer Destination byte vector; replaced.
540  * @return @c true when any data was copied.
541  */
542  bool read_all_output(std::vector<uint8_t>& buffer);
543 
544  /**
545  * @brief Drains all buffered stderr into @p buffer.
546  *
547  * @param buffer Destination byte vector; replaced.
548  * @return @c true when any data was copied.
549  */
550  bool read_all_error(std::vector<uint8_t>& buffer);
551 
552  /**
553  * @brief Drains all buffered stdout and stderr into @p buffer.
554  *
555  * @param buffer Destination byte vector; replaced.
556  * @return @c true when any data was copied.
557  */
558  bool read_all(std::vector<uint8_t>& buffer);
559 
560  /**
561  * @brief Drains all buffered stdout into @p str.
562  *
563  * @param str Destination string; replaced.
564  * @return @c true when any data was copied.
565  */
566  bool read_all_output(std::string& str);
567 
568  /**
569  * @brief Drains all buffered stderr into @p str.
570  *
571  * @param str Destination string; replaced.
572  * @return @c true when any data was copied.
573  */
574  bool read_all_error(std::string& str);
575 
576  /**
577  * @brief Drains all buffered stdout and stderr into @p str.
578  *
579  * @param str Destination string; replaced.
580  * @return @c true when any data was copied.
581  */
582  bool read_all(std::string& str);
583 
584  /**
585  * @brief Writes a byte buffer to the child's stdin.
586  *
587  * @param buffer Bytes to write.
588  * @param timeout_ms Maximum wait in milliseconds. Default: @c kDefaultWriteTimeoutMs.
589  * @return Number of bytes actually written.
590  */
591  size_t write(const std::vector<uint8_t>& buffer, int timeout_ms = kDefaultWriteTimeoutMs);
592 
593  /**
594  * @brief Writes a string to the child's stdin.
595  *
596  * @param str String to write.
597  * @param timeout_ms Maximum wait in milliseconds. Default: @c kDefaultWriteTimeoutMs.
598  * @return Number of bytes actually written.
599  */
600  size_t write(const std::string& str, int timeout_ms = kDefaultWriteTimeoutMs);
601 
602  /**
603  * @brief Closes the stdin pipe, signalling EOF to the child.
604  *
605  * @warning Must not run concurrently with @c write() or @c close() on the same object: the
606  * stdin descriptor is read and closed without synchronisation, so an overlapping
607  * call can write to a descriptor number the operating system has already reused.
608  * Serialise stdin operations in the caller.
609  */
611 
612  /**
613  * @brief Synchronously executes a program and returns its exit code.
614  *
615  * @details
616  * The child's output is not forwarded anywhere, but it is still drained into the internal
617  * stdout and stderr buffers, each capped at the default 16 MiB, so a very chatty command holds
618  * that much memory for the duration of the call. Returns @c -1 when the launch fails or the timeout
619  * elapses.
620  *
621  * @param program Path to the executable.
622  * @param arguments Argument vector. Default: empty.
623  * @param timeout_ms Maximum wait in milliseconds. Default: @c kDefaultExecuteTimeoutMs.
624  * @return Exit code on success, or @c -1 on failure.
625  */
626  static int execute(const std::string& program, const std::vector<std::string>& arguments = {},
627  int timeout_ms = kDefaultExecuteTimeoutMs);
628 
629  /**
630  * @brief Launches a program detached from the calling process and returns immediately.
631  *
632  * @param program Path to the executable.
633  * @param arguments Argument vector. Default: empty.
634  * @return @c true when the OS reports a successful launch.
635  */
636  static bool start_detached(const std::string& program, const std::vector<std::string>& arguments = {});
637 
638  private:
639  struct ReadResult final {
640  bool has_stdout_data{false};
641  bool has_stderr_data{false};
642  bool truncated{false};
643  bool read_error{false};
644  };
645 
646  void set_state(State state);
647 
648  void set_error(Error error);
649 
650  void cleanup();
651 
652  ReadResult read_from_pipes();
653 
654  void report_read_result(const ReadResult& result, bool notify_data = true);
655 
656  void read_from_pipes_with_lock();
657 
658  bool setup_pipes();
659 
660  bool start_program(const std::string& program, const std::vector<std::string>& arguments);
661 
662  void monitor_thread();
663 
664  void start_monitor_thread();
665 
666  void stop_monitor_thread();
667 
668  void handle_process_exit(int exit_code, ExitStatus status);
669 
670  void invoke_callbacks_outside_lock(Error error_to_report, bool has_finished, int exit_code_to_report,
671  ExitStatus exit_status_to_report, State state_to_report, bool has_state_changed,
672  bool has_stdout_data, bool has_stderr_data);
673 
674  struct Impl;
675  std::unique_ptr<Impl> impl_;
676 
678 };
679 
680 } // namespace vlink
Pool-backed type-erased callables: copyable vlink::Function and move-only vlink::MoveFunction.
Cross-platform macros for visibility, branch hints, copy prevention, singletons and string helpers.
#define VLINK_EXPORT
Definition: macros.h:81
#define VLINK_DISALLOW_COPY_AND_ASSIGN(classname)
Deletes the copy constructor and copy-assignment operator of classname.
Definition: macros.h:174