Add a function for searching through PATH

This commit is contained in:
Robbert van der Helm
2022-04-14 18:08:00 +02:00
parent 33b49dd7a5
commit b6e63ea0d5
2 changed files with 21 additions and 0 deletions
+13
View File
@@ -66,6 +66,19 @@ std::vector<ghc::filesystem::path> split_path(
return search_path;
}
std::optional<ghc::filesystem::path> search_in_path(
const std::vector<ghc::filesystem::path>& path,
const std::string_view& target) {
for (const auto& dir : path) {
ghc::filesystem::path candidate = dir / target;
if (access(candidate.c_str(), X_OK) == 0) {
return candidate;
}
}
return std::nullopt;
}
ProcessEnvironment::ProcessEnvironment(char** initial_env) {
// We'll need to read all strings from `initial_env`. They _should_ all be
// zero-terminated strings, with a null pointer to indicate the end of the
+8
View File
@@ -47,6 +47,14 @@ bool pid_running(pid_t pid);
*/
std::vector<ghc::filesystem::path> split_path(const std::string_view& path_env);
/**
* Search through a search path vector created by `split_path` for an executable
* binary called `target`, returning the first match if any.
*/
std::optional<ghc::filesystem::path> search_in_path(
const std::vector<ghc::filesystem::path>& path,
const std::string_view& target);
/**
* Helper to create an `environ`-like environment object for passing to the
* `exec*e()` family of functions.