### Setting Process Start Directory Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Example of launching a process with a specified working directory using `process_start_dir`. Demonstrates setting the execution context for the child process. ```C++ asio::io_context ctx; process ls(ctx.get_executor(), "/ls", {}, process_start_dir("/home")); ls.wait(); ``` -------------------------------- ### Process Quickstart Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Illustrates the basic requirements for launching a process using Boost.Process, including an executor, executable path, arguments, and initializers. ```APIDOC ## POST /process/quickstart ### Description Launches a process with the specified executor, executable path, arguments, and initializers. The launched process can be subsequently awaited or terminated. ### Method POST ### Endpoint /process/quickstart ### Parameters #### Request Body - **executor** (asio::any_io_executor) - Required - The executor context for the process. - **executable_path** (filesystem::path) - Required - The path to the executable file. - **arguments** (range) - Required - A list of arguments for the executable. - **initializers** (...) - Optional - Variadic set of initializers to modify process behavior. ### Request Example ```json { "executor": "", "executable_path": "/usr/bin/cp", "arguments": ["source.txt", "target.txt"] } ``` ### Response #### Success Response (200) - **process_handle** (process) - A handle to the launched process. #### Response Example ```json { "process_handle": "" } ``` ``` -------------------------------- ### C++: Example Usage of Creation Flags Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Demonstrates how to use Boost.Process creation flags, such as `create_new_console`, when launching a new process. ```cpp process p{"C:\\not-a-virus.exe", {}, process::windows::create_new_console}; ``` -------------------------------- ### Process Start Directory Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Demonstrates how to use the `process_start_dir` initializer to specify the working directory for a subprocess. ```APIDOC ## `process_start_dir` Initializer This initializer allows you to set the starting directory for a process. ### Example ```cpp asio::io_context ctx; process ls(ctx.get_executor(), "/ls", {}, process_start_dir("/home")); ls.wait(); ``` This will run `ls` in the `/home` directory instead of the current directory. **Note:** If your path is relative, it may fail on POSIX systems because the directory is changed before calling `execve`. ``` -------------------------------- ### Boost.Process v2 Simplified Interface Example Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Illustrates the cleaner and more scalable interface of Boost.Process v2. It shows how to initialize a process with its context, executable, arguments, stdio configuration, and environment variables, addressing each logical component separately. ```cpp extern std::unordered_map my_env; extern asio::io_context ctx; process proc(ctx, "./test", {"--help"}, process_stdio{nullptr, {}, {}}, process_environment(my_env)); ``` -------------------------------- ### Use a Custom Launcher (Windows C++) Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Example of using a specific Windows launcher, `windows::as_user_launcher`, to create a process with user privileges. It involves obtaining a launcher instance and invoking it with process details. ```cpp auto l = windows::as_user_launcher((HANDLE)0xDEADBEEF); asio::io_context ctx; boost::system::error_code ec; auto proc = l(ctx, ec, "C:\\User\\boost\\Downloads\\totally_not_a_virus.exe", {}); ``` -------------------------------- ### Process Starting Directory Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index The `process_start_dir` struct is used to specify the initial working directory for a subprocess. ```APIDOC ## `start_dir.hpp` ### Description Initializer for the starting directory of a subprocess. ### Structure ```cpp struct process_start_dir { filesystem::path start_dir; process_start_dir(filesystem::path start_dir); }; ``` ``` -------------------------------- ### Boost.Process v1 Simplified Interface Example Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Demonstrates the simplified interface for defining process settings in Boost.Process v1 using a small DSL within the constructor. This syntax allows for setting executable, arguments, standard input, and environment variables. ```cpp child c{exe="test", args+="--help", std_in < null(), env["FOO"] += "BAR"}; ``` -------------------------------- ### Boost.Process Subprocess Starting Directory Initializer Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Defines the `process_start_dir` struct for specifying the working directory of a launched subprocess. It takes a `filesystem::path` as input during initialization. ```cpp /// Initializer for the starting directory of a subprocess to be launched. struct process_start_dir { filesystem::path start_dir; process_start_dir(filesystem::path start_dir); { } }; ``` -------------------------------- ### Boost.Process Subprocess Standard I/O Initialization Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Illustrates initializing the standard input, output, and error streams for a subprocess. It shows default inheritance, explicit null device assignment, and examples for C++17 and older standards. ```cpp asio::io_context ctx; v2::process proc(ctx, "/bin/bash", {}, v2::process_stdio{}); ``` ```cpp asio::io_context ctx; /// C++17 v2::process proc17(ctx, "/bin/bash", {}, v2::process_stdio{.err=nullptr}); /// C++11 & C++14 v2::process proc17(ctx, "/bin/bash", {}, v2::process_stdio{ {}, {}, nullptr}); ``` -------------------------------- ### Windows custom_initializer Interface Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Defines the interface for custom initializers on Windows, specifying callbacks for setup, error handling, and success during process creation. ```C++ struct custom_initializer { // called before a call to CreateProcess. A returned error will cancel the launch. template error_code on_setup(Launcher & launcher, const filesystem::path &executable, std::wstring &cmd_line); // called for every initializer if an error occurred during setup or process creation template void on_error(Launcher & launcher, const filesystem::path &executable, std::wstring &cmd_line, const error_code & ec); // called after successful process creation template void on_success(Launcher & launcher, const filesystem::path &executable, std::wstring &cmd_line); }; ``` -------------------------------- ### Linux custom_initializer Interface Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Defines the interface for custom initializers on Linux, specifying callbacks for setup, error handling, success, fork errors, and exec setup/errors. ```C++ struct custom_initializer { // called before a call to fork. A returned error will cancel the launch. template error_code on_setup(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line)); // called for every initializer if an error occurred during setup or process creation template void on_error(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line), const error_code & ec); // called after successful process creation template void on_success(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line)); // called for every initializer if an error occurred when forking, in addition to on_error. template void on_fork_error(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line), const error_code & ec); // called before a call to execve. A returned error will cancel the launch. Called from the child process. template error_code on_exec_setup(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line)); // called after a failed call to execve from the child process. template void on_exec_error(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line)); }; ``` -------------------------------- ### C++ Process Environment Setup Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Demonstrates how to set the environment for a child process using `process_environment`. The environment initializer can be reused for multiple processes. Note that the OS may modify the internal state. ```cpp process proc{executor, find_executable("printenv"), {"foo"}, process_environment{"foo=bar"}}; ``` ```cpp auto exe = find_executable("printenv"); process_environment env = {"FOO=BAR", "BAR=FOO"}; process proc1(executor, exe, {"FOO"}, env); process proc2(executor, exe, {"BAR"}, env); ``` -------------------------------- ### C++: Example Usage of Show Window Flags Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Illustrates the usage of Boost.Process `show_window` flags, like `show_window_minimized`, to control the initial display state of a child process's window. ```cpp process p{"C:\\not-a-virus.exe", {}, process::windows::show_window_minimized}; ``` -------------------------------- ### Start Process and Connect Pipes with popen Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Initiate a subprocess and establish pipes for its standard input and output using the `popen` class. This allows the `popen` object to be used directly as a stream, simplifying interaction with the subprocess's I/O. ```cpp asio::io_context ctx; boost::process::popen proc(ctx, "/usr/bin/addr2line", {argv[0]}); asio::write(proc, asio::buffer("main\n")); std::string line; asio::read_until(proc, asio::dynamic_buffer(line), '\n'); ``` -------------------------------- ### Get Home Directory Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Finds the home directory within a given environment. Defaults to the current process's environment if none is specified. ```APIDOC ## Function: home ### Description Find the home folder in an environment-like type. ### Parameters - `Environment && env`: The environment to search. Defaults to the current environment of this process. ### Returns A `filesystem::path` to the home directory or an empty path if it cannot be found. ### Example Usage ```cpp #include #include int main() { boost::filesystem::path home_dir = boost::process::home(); if (!home_dir.empty()) { std::cout << "Home directory: " << home_dir << std::endl; } return 0; } ``` ``` -------------------------------- ### Get Process Command Line Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Retrieves the command line used to launch a process. Supports operations on a process handle or by process ID. May fail on some platforms. ```cpp // Get the cmd line used to launche the process template shell cmd(basic_process_handle & handle, error_code & ec); template shell cmd(basic_process_handle & handle); shell cmd(pid_type pid, error_code & ec); shell cmd(pid_type pid); ``` -------------------------------- ### Key-Value Pair View Tuple-like Getters in C++ Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Specialized `get` methods for `key_value_pair_view` that enable tuple-like access to its key and value components. This supports structured bindings in C++17 and later. ```C++ template inline auto get() const -> typename conditional::type; ``` -------------------------------- ### Get Environment Variable Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Retrieves the value of a specific environment variable from the current process. ```APIDOC ## Function: get (Environment Variable) ### Description Get an environment variable from the current process. ### Parameters - `const key & k`: The key of the environment variable to retrieve. - `error_code & ec`: An error code object to store any errors that occur. ### Returns A `value` object representing the environment variable's value. ### Example Usage ```cpp #include #include int main() { boost::system::error_code ec; boost::process::value var_value = boost::process::get("PATH", ec); if (!ec) { std::cout << "PATH = " << var_value.string() << std::endl; } else { std::cerr << "Error getting PATH: " << ec.message() << std::endl; } return 0; } ``` ``` -------------------------------- ### Process Construction and Initialization (C++) Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Provides various constructors for `basic_process` to launch new processes. This includes launching from properties, executables, arguments, and attaching to existing processes. ```cpp // Move construct the process. It will be detached from `lhs`. basic_process(basic_process&& lhs) = default; // Move assign a process. It will be detached from `lhs`. basic_process& operator=(basic_process&& lhs) = default; // Move construct and rebind the executor. template basic_process(basic_process&& lhs); // Construct a child from a property list and launch it using the default launcher.. template explicit basic_process( executor_type executor, const filesystem::path& exe, std::initializer_list args, Inits&&... inits); // Construct a child from a property list and launch it using the default launcher.. template explicit basic_process( executor_type executor, const filesystem::path& exe, Args&& args, Inits&&... inits); // Construct a child from a property list and launch it using the default launcher.. template explicit basic_process( ExecutionContext & context, const filesystem::path& exe, std::initializer_list args, Inits&&... inits); // Construct a child from a property list and launch it using the default launcher. template explicit basic_process( ExecutionContext & context, const filesystem::path&>::type exe, Args&& args, Inits&&... inits); // Attach to an existing process explicit basic_process(executor_type exec, pid_type pid); // Attach to an existing process and the internal handle explicit basic_process(executor_type exec, pid_type pid, native_handle_type native_handle); // Create an invalid handle explicit basic_process(executor_type exec); // Attach to an existing process template explicit basic_process(ExecutionContext & context, pid_type pid); // Attach to an existing process and the internal handle template explicit basic_process(ExecutionContext & context, pid_type pid, native_handle_type native_handle); // Create an invalid handle template explicit basic_process(ExecutionContext & context); ``` -------------------------------- ### Get Process ID (C++) Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Obtains the unique identifier (PID) of a process. This method is provided by the Boost.Process library for process identification. ```C++ // Get the id of the process; pid_type id() const; ``` -------------------------------- ### Create a process using default_launcher in C++ Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Demonstrates how to create a process using the default_launcher, which is the standard method for process creation in the Boost Process library. It shows an equivalent initialization using both direct process instantiation and the default_launcher functor. ```C++ asio::io_context ctx; process proc(ctx.get_executor(), "test", {}); // equivalent to process prod = default_launcher()(ctx.get_executor(), "test", {}); ``` -------------------------------- ### FILE* for I/O Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Illustrates how to use `FILE*` streams for standard input, output, and error redirection. ```APIDOC ## `FILE*` for I/O `FILE*` can be used for stdin, stdout, and stderr. ### Example redirecting stderr and stdout to stdout ```cpp asio::io_context ctx; // forward both stderr & stdout to stdout of the parent process process proc(ctx, "/usr/bin/g++", {"--version"}, process_stdio{{ /* in to default */}, stdout, stdout}); proc.wait(); ``` ``` -------------------------------- ### Process Launchers Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Provides information on various process launchers available, including their system availability and default usage. ```APIDOC ## GET /launchers ### Description Retrieves a list of available process launchers, their summaries, default system usage, and availability. ### Method GET ### Endpoint /launchers ### Response #### Success Response (200) - **launchers** (array) - A list of launcher details. - **name** (string) - The name of the launcher. - **summary** (string) - A brief description of the launcher. - **default_on** (string) - The system(s) where this launcher is the default. - **available_on** (string) - The system(s) where this launcher is available. #### Response Example ```json { "launchers": [ { "name": "windows::default_launcher", "summary": "CreateProcessW", "default_on": "windows", "available_on": "windows" }, { "name": "posix::default_launcher", "summary": "fork & an error pipe", "default_on": "most of posix", "available_on": "posix" } ] } ``` ``` -------------------------------- ### Launch a Process with Arguments (C++) Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Demonstrates launching a process with a specified executable, arguments, and an executor. The process handle can then be awaited or terminated. ```cpp process proc(ctx.get_executor(), "/usr/bin/cp", {"source.txt", "target.txt"}); ``` -------------------------------- ### Linux Launchers and Custom Initializer Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Explains how Linux launchers handle errors via pipes and introduces the `custom_initializer` struct with its various callback methods for managing the process lifecycle. ```APIDOC ## Linux Launchers The default launchers on Linux open an internal pipe to communicate errors that occur after forking back to the parent process. - A pipe can be used if one end is open on the parent, the other on the child. This allows the parents to select on his pipe-end to know if the child exited. - This can be prevented by using the `fork_and_forget_launcher`. - Alternatively, the `vfork_launcher` can report errors directly back to the parent process. ### `custom_initializer` Structure This structure defines callbacks for various stages of the process launch. #### Methods - `error_code on_setup(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line))` - Called before a call to fork. A returned error will cancel the launch. - `void on_error(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line), const error_code & ec)` - Called for every initializer if an error occurred during setup or process creation. - `void on_success(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line))` - Called after successful process creation. - `void on_fork_error(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line), const error_code & ec)` - Called for every initializer if an error occurred when forking, in addition to `on_error`. - `error_code on_exec_setup(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line))` - Called before a call to `execve`. A returned error will cancel the launch. Called from the child process. - `void on_exec_error(Launcher & launcher, const filesystem::path &executable, const char * const * (&cmd_line))` - Called after a failed call to `execve` from the child process. **Note:** The launcher will close all non-whitelisted file descriptors after `on_exec_setup`. ``` -------------------------------- ### Windows Launchers and Custom Initializer Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Details the Windows launcher behavior, which calls specific functions on the initializer if present, and outlines the `custom_initializer` structure for Windows. ```APIDOC ## Windows Launchers Windows launchers call the following functions on the `custom_initializer` if present. ### `custom_initializer` Structure for Windows - `error_code on_setup(Launcher & launcher, const filesystem::path &executable, std::wstring &cmd_line)` - Called before a call to `CreateProcess`. A returned error will cancel the launch. - `void on_error(Launcher & launcher, const filesystem::path &executable, std::wstring &cmd_line, const error_code & ec)` - Called for every initializer if an error occurred during setup or process creation. - `void on_success(Launcher & launcher, const filesystem::path &executable, std::wstring &cmd_line)` - Called after successful process creation. **Note:** All additional launchers for Windows inherit `default_launcher`. ``` -------------------------------- ### String View Iterator Access in C++ Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Provides methods to get iterators to the beginning and end of the string view's content. These are essential for range-based operations and algorithms. ```C++ value_iterator begin() const; value_iterator end() const; ``` -------------------------------- ### Redirecting Streams to Parent's stdout Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Example showing how to redirect both stderr and stdout of a child process to the parent process's stdout stream using `stdout`. ```C++ asio::io_context ctx; // forward both stderr & stdout to stdout of the parent process process proc(ctx, "/usr/bin/g++", {"--version"}, process_stdio{{ /* in to default */}, stdout, stdout}); proc.wait(); ``` -------------------------------- ### Get Native Process Handle (C++) Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Accesses the native handle of a process. This might be undefined on POSIX systems that only support signals. It's a key feature of the Boost.Process library. ```C++ // The native handle of the process. /** This might be undefined on posix systems that only support signals */ native_exit_code_type native_exit_code() const; ``` -------------------------------- ### Pipes for I/O Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Shows how to use `asio::readable_pipe` for standard output and how to read from it. ```APIDOC ## Pipes for I/O Asio pipes can be used for I/O. When used with `process_stdio`, they are automatically connected and assigned to the child process. ### Example with `readable_pipe` ```cpp asio::io_context ctx; asio::readable_pipe rp{ctx}; process proc(ctx, "/usr/bin/g++", {"--version"}, process_stdio{{ /* in to default */}, rp, { /* err to default */ }}); std::string output; boost::system::error_code ec; asio::read(rp, asio::dynamic_buffer(output), ec); assert(!ec || (ec == asio::error::eof)); proc.wait(); ``` - `readable_pipe` can be assigned to `out` and `err`. - `writable_pipe` can be assigned to `in`. ``` -------------------------------- ### Launching a process and interacting with pipes (C++) Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index This snippet demonstrates how to launch an external process (`addr2line`) using Boost.Process, write data to its standard input, and read from its standard output. It utilizes `asio::write` and `asio::read_until` for stream operations. ```cpp popen proc(executor, find_executable("addr2line"), {argv[0]}); asio::write(proc, asio::buffer("main\n")); std::string line; asio::read_until(proc, asio::dynamic_buffer(line), '\n'); ``` -------------------------------- ### Get Process Executable Path Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Retrieves the path to the executable file of a process. Functions are provided for process handles and process IDs. Operation might fail on certain platforms. ```cpp // Get the executable of the process. template filesystem::path exe(basic_process_handle & handle, error_code & ec); template filesystem::path exe(basic_process_handle & handle) filesystem::path exe(pid_type pid, error_code & ec); filesystem::path exe(pid_type pid); ``` -------------------------------- ### Get Process Current Working Directory Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Retrieves the current working directory of a process. Functions are available for process handles and process IDs. Some platforms may not support this operation. ```cpp // Get the current working directory of the process. template filesystem::path cwd(basic_process_handle & handle, error_code & ec); template filesystem::path cwd(basic_process_handle & handle) filesystem::path cwd(pid_type pid, error_code & ec); filesystem::path cwd(pid_type pid); ``` -------------------------------- ### Value Iterators and Data Access Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Provides methods to access the begin and end iterators for a `value` and retrieve a pointer to the underlying data. Also includes a method to get the size. ```cpp value_iterator begin() const; value_iterator end() const; const value_type * data() const; std::size_t size() const; ``` -------------------------------- ### basic_popen Constructors Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Details on the various constructors available for the `basic_popen` class, allowing for different initialization methods. ```APIDOC ## Constructors for `basic_popen` ### Create a closed process handle ```cpp explicit basic_popen(executor_type exec); ``` ```cpp template explicit basic_popen(ExecutionContext & context); ``` ### Construct a child from a property list and launch it ```cpp template explicit basic_popen( executor_type executor, const filesystem::path& exe, std::initializer_list args, Inits&&... inits); ``` ```cpp template explicit basic_popen( Launcher && launcher, executor_type executor, const filesystem::path& exe, std::initializer_list args, Inits&&... inits); ``` ```cpp template explicit basic_popen( executor_type executor, const filesystem::path& exe, Args&& args, Inits&&... inits); ``` ```cpp template explicit basic_popen( Launcher && launcher, executor_type executor, const filesystem::path& exe, Args&& args, Inits&&... inits); ``` ```cpp template explicit basic_popen( ExecutionContext & context, const filesystem::path& exe, std::initializer_list args, Inits&&... inits); ``` ```cpp template explicit basic_popen( Launcher && launcher, ExecutionContext & context, const filesystem::path& exe, std::initializer_list args, Inits&&... inits); ``` ```cpp template explicit basic_popen( ExecutionContext & context, const filesystem::path& exe, Args&& args, Inits&&... inits); ``` ```cpp template explicit basic_popen( Launcher && launcher, ExecutionContext & context, const filesystem::path& exe, Args&& args, Inits&&... inits); ``` ``` -------------------------------- ### Get Process Exit Code (C++) Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Retrieves the evaluated exit code of a process. This function is part of the Boost.Process library and returns an integer representing the process's exit status. ```C++ // Return the evaluated exit_code. int exit_code() const; ``` -------------------------------- ### Bind Initializers to Launcher Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Create a new process launcher with specific initializers already bound to it. This utility simplifies the creation of customized launchers by pre-configuring parameters like environment variables or stream settings. ```cpp // Creates a new launcher with the bound initializer. template auto bind_launcher(Launcher && launcher, Init && ... init); // Calls bind_launcher with the default_launcher as the first parameter. // The new launcher with bound parameters template auto bind_default_launcher(Init && ... init); ``` -------------------------------- ### popen.hpp - basic_popen Class Overview Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Provides an overview of the `basic_popen` class functionality for launching and managing child processes. ```APIDOC ## `popen.hpp` `popen` is a class that launches a process and connect stdin & stderr to pipes. ### Example Usage ```cpp popen proc(executor, find_executable("addr2line"), {argv[0]}); asio::write(proc, asio::buffer("main\n")); std::string line; asio::read_until(proc, asio::dynamic_buffer(line), '\n'); ``` ### `basic_popen` Class A subprocess with automatically assigned pipes. ```cpp template struct basic_popen : basic_process { // ... constructors and members ... }; ``` ``` -------------------------------- ### Key Class Methods Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index This section details the various methods available for the Key class, including assignment, comparison, and conversion. ```APIDOC ## Key Class Methods ### Description Provides methods for managing key objects, including assignment, comparison, and conversion to string representations. ### Methods - **Assignment Operators:** - `key& operator=( const key& p ) = default;` - `key& operator=( key&& p );` - `key& operator=( string_type&& source );` - `template< class Source > key& operator=( const Source& source );` - **Assignment Methods:** - `key& assign( string_type&& source );` - `template< class Source > key& assign( const Source& source );` - `template< class InputIt > key& assign( InputIt first, InputIt last );` - **Utility Methods:** - `void clear();` - `void swap( key& other ) noexcept;` - `const value_type* c_str() const noexcept;` - `const string_type& native() const noexcept;` - `string_view_type native_view() const noexcept;` - `bool empty() const; - **Conversion Operators:** - `operator string_type() const;` - `operator string_view_type() const;` - **Comparison Methods:** - `int compare( const key& p ) const noexcept;` - `int compare( const string_type& str ) const;` - `int compare( string_view_type str ) const;` - `int compare( const value_type* s ) const;` - **String Conversion:** - `template< class CharT, class Traits = std::char_traits, class Alloc = std::allocator > std::basic_string basic_string( const Alloc& alloc = Alloc()) const;` - `std::string string() const;` - `std::wstring wstring() const;` - `const string_type & native_string() const;` - **Friend Operators:** - `friend bool operator==(const key & l, const key & r);` - `friend bool operator!=(const key & l, const key & r);` - `friend bool operator<=(const key & l, const key & r);` - `friend bool operator>=(const key & l, const key & r);` - `friend bool operator< (const key & l, const key & r);` - `friend bool operator> (const key & l, const key & r);` - `template< class CharT, class Traits > friend std::basic_ostream& operator<<( std::basic_ostream& os, const key& p );` - `template< class CharT, class Traits > friend std::basic_istream& operator>>( std::basic_istream& is, key& p );` - **Accessors:** - `const value_type * data() const;` - `std::size_t size() const; ``` -------------------------------- ### Executing Processes Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Explains how to execute processes synchronously and asynchronously using `execute` and `async_execute` from `execute.hpp`. ```APIDOC ## Process Execution ### Description Functions for executing processes, both synchronously and asynchronously, with support for cancellation. ### Synchronous Execution ```cpp // Execute a process and wait for it to complete template int execute(basic_process proc); // Execute a process and wait, with error code template int execute(basic_process proc, error_code & ec); ``` ### Asynchronous Execution ```cpp // Execute a process asynchronously and handle completion template> auto async_execute(basic_process proc, WaitHandler && handler = net::default_completion_token_t()); ``` ### Cancellation Handling Cancelling `async_execute` affects the child process as follows: - `cancellation_type::total` → interrupt - `cancellation_type::partial` → request_exit - `cancellation_type::terminal` → terminate Note that a subprocess might ignore signals not related to termination. ``` -------------------------------- ### Boost.Process: Async Read Operation Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Starts an asynchronous read operation from the process's standard output. It takes a mutable buffer sequence and a completion token, returning the number of bytes read and any error code. ```cpp template > auto async_read_some(const MutableBufferSequence& buffers, BOOST_ASIO_MOVE_ARG(ReadToken) token = net::default_completion_token_t()); ``` -------------------------------- ### Process Information Retrieval Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index The `ext` module provides functions to retrieve information about third-party processes, including their command line, current working directory, environment, and executable path. ```APIDOC ## `ext` Module ### Description Provides features to obtain information about third-party processes. ### Functions **Get Command Line:** - `shell cmd(basic_process_handle & handle, error_code & ec)` - `shell cmd(basic_process_handle & handle)` - `shell cmd(pid_type pid, error_code & ec)` - `shell cmd(pid_type pid)` **Get Current Working Directory:** - `filesystem::path cwd(basic_process_handle & handle, error_code & ec)` - `filesystem::path cwd(basic_process_handle & handle)` - `filesystem::path cwd(pid_type pid, error_code & ec)` - `filesystem::path cwd(pid_type pid)` **Get Process Environment:** - `env_view env(basic_process_handle & handle, error_code & ec)` - `env_view env(basic_process_handle & handle)` - `env_view env(pid_type pid, error_code & ec)` - `env_view env(pid_type pid)` **Get Executable Path:** - `filesystem::path exe(basic_process_handle & handle, error_code & ec)` - `filesystem::path exe(basic_process_handle & handle)` - `filesystem::path exe(pid_type pid, error_code & ec)` - `filesystem::path exe(pid_type pid)` ### Notes - Functions may fail with `operation_not_supported` on some platforms. - Overloads taking a `HANDLE` are available on Windows. ``` -------------------------------- ### Get Process Environment Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Retrieves the environment variables of a process. Supports access via process handle or process ID. Note: 'env_view cwd' in the original text seems to be a typo and likely meant 'env_view env'. ```cpp // Get the current environment of the process. template env_view cwd(basic_process_handle & handle, error_code & ec); template env_view cwd(basic_process_handle & handle) env_view env(pid_type pid, error_code & ec); env_view env(pid_type pid); ``` -------------------------------- ### windows/creation_flags.hpp Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Platform-specific creation flags for Windows, allowing fine-grained control over process creation. Includes options for new process groups, breaking away from job objects, and new consoles. ```APIDOC ## `windows/creation_flags.hpp` ### Description Creation flags allow explicitly setting `dwFlags` for process creation on Windows. These flags control various aspects of the new process, such as its process group and console. ### Available Flags - `create_new_process_group`: Creates a new process group. Necessary to allow interrupts for the subprocess. - `create_breakaway_from_job`: Breaks away from the current job object. - `create_new_console`: Allocates a new console for the process. ### Usage Example ```cpp process p{"C:\\not-a-virus.exe", {}, process::windows::create_new_console}; ``` ``` -------------------------------- ### Getting Environment Variables Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Retrieves the value of an environment variable. Overloads are provided for different key types (including `key` and C-style strings) and for error handling via `error_code`. If an error occurs and `error_code` is provided, it will be set. ```cpp value get(const key & k, error_code & ec); value get(const key & k); value get(basic_cstring_ref> k, error_code & ec); value get(basic_cstring_ref> k); value get(const char_type * c, error_code & ec); value get(const char_type * c); ``` -------------------------------- ### Key-Value Pair View Constructor in C++ Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Constructors for `key_value_pair_view`, including default, copy, move, from various string-like sources, and C-style strings. These allow flexible initialization of key-value pairs. ```C++ key_value_pair_view() noexcept = default; key_value_pair_view( const key_value_pair_view& p ) = default; key_value_pair_view( key_value_pair_view&& p ) noexcept = default; template::value>::type> key_value_pair_view( const Source& source ); key_value_pair_view( const char_type * p); key_value_pair_view( char_type * p); ``` -------------------------------- ### Process ID Management Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Provides utilities for managing process IDs, including getting the current process ID, listing all available PIDs, and retrieving parent or child PIDs. An integral type `pid_type` is defined for process identifiers. ```cpp //An integral type representing a process id. typedef implementation_defined pid_type; // Get the process id of the current process. pid_type current_pid(); // List all available pids. std::vector all_pids(boost::system::error_code & ec); std::vector all_pids(); // return parent pid of pid. pid_type parent_pid(pid_type pid, boost::system::error_code & ec); pid_type parent_pid(pid_type pid); // return child pids of pid. std::vector child_pids(pid_type pid, boost::system::error_code & ec); std::vector child_pids(pid_type pid); ``` -------------------------------- ### Retrieve Process Command Line with Boost.Process Extensions Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Provides functions to retrieve the command line used to launch a process. It supports fetching via a process handle or a process ID (PID) and includes error handling. ```cpp // Get the cmd line used to launche the process template shell cmd(basic_process_handle & handle, error_code & ec); template shell cmd(basic_process_handle & handle); shell cmd(pid_type pid, error_code & ec); shell cmd(pid_type pid); ``` -------------------------------- ### All Process IDs Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Lists all currently available process IDs on the system. ```APIDOC ## GET /process/all_pids ### Description Retrieves a list of all process IDs that are currently running on the system. ### Method GET ### Endpoint /process/all_pids ### Response #### Success Response (200) - **pids** (array) - An array of process IDs. #### Response Example ```json { "pids": [1, 12345, 54321] } ``` ``` -------------------------------- ### Accessing Environment Variables in Boost.Process Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Demonstrates how to iterate through environment variables of the current process. The `current_view` struct provides an interface to access environment variables as key-value pairs. This example shows a simple loop to print each environment variable. ```cpp void dump_my_env(current_view env = current()) { for (auto & [k, v] : env) std::cout << k.string() << " = " << v.string() << std::endl; } ``` -------------------------------- ### Retrieve Process Current Working Directory with Boost.Process Extensions Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Offers functions to get the current working directory (CWD) of a process. It allows retrieving the CWD using either a process handle or a PID, with optional error code parameters. ```cpp // Get the current working directory of the process. template filesystem::path cwd(basic_process_handle & handle, error_code & ec); template filesystem::path cwd(basic_process_handle & handle) filesystem::path cwd(pid_type pid, error_code & ec); filesystem::path cwd(pid_type pid); ``` -------------------------------- ### Parse and Execute Shell Commands with Boost.Process Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Demonstrates parsing a shell command line into executable and arguments, with a security check before launching a process. It utilizes the `shell` class to tokenize the command and `process` to execute it. ```cpp asio::io_context ctx; auto cmd = shell("my-app --help"); auto exe = cmd.exe(); check_if_malicious(exe); process proc{ctx, exe, cmd.args()}; ``` -------------------------------- ### Process Environment Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Demonstrates how to set the environment for a child process using `process_environment`. The environment initializer can be reused. ```APIDOC ## Process Environment Setup ### Description Manages the environment variables for child processes. ### Usage Examples ```cpp // Set a single environment variable process_environment env = {"FOO=BAR"}; // Set multiple environment variables process_environment multi_env = {"VAR1=VALUE1", "VAR2=VALUE2"}; // Using process_environment with process constructor process proc{executor, find_executable("printenv"), {"foo"}, process_environment{"foo=bar"}}; // Reusing process_environment auto exe = find_executable("printenv"); process_environment env = {"FOO=BAR", "BAR=FOO"}; process proc1(executor, exe, {"FOO"}, env); process proc2(executor, exe, {"BAR"}, env); ``` ``` -------------------------------- ### default_launcher overloads in C++ Source: https://www.boost.org/doc/libs/1_89_0/libs/process/doc/html/index Details the various overloads available for the default_launcher function in the Boost Process library. These overloads cater to different initialization requirements, including context types, error handling, and argument forwarding. ```C++ (ExecutionContext &, filesystem::path, Args && args, Inits && ... inits) -> basic_process (Executor &, filesystem::path, Args && args, Inits && ... inits) -> basic_process; (ExecutionContext &, error_code&, filesystem::path, Args && args, Inits && ... inits) -> basic_process;` (Executor &, error_code&, filesystem::path, Args && args, Inits && ... inits) -> basic_process ```