From a7b978412c3301648b5136ac40a573b1f1e94b2f Mon Sep 17 00:00:00 2001 From: TheDoctor314 Date: Wed, 29 Sep 2021 00:02:26 +0530 Subject: [PATCH] Add env parameter to exec_sh() Before passing the cmd to exec() we set the required environment variables. Also add the test for it. --- include/utils/process.hpp | 2 +- src/utils/process.cpp | 7 ++++++- tests/unit_tests/utils/process.cpp | 10 ++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/include/utils/process.hpp b/include/utils/process.hpp index 3ab5fd7b..c080ca8d 100644 --- a/include/utils/process.hpp +++ b/include/utils/process.hpp @@ -16,7 +16,7 @@ namespace process_util { void fork_detached(std::function const& lambda); void exec(char* cmd, char** args); - void exec_sh(const char* cmd); + void exec_sh(const char* cmd, const vector>& env = {}); int wait(pid_t pid); diff --git a/src/utils/process.cpp b/src/utils/process.cpp index 1127c606..dc4ef4c2 100644 --- a/src/utils/process.cpp +++ b/src/utils/process.cpp @@ -124,9 +124,14 @@ namespace process_util { /** * Execute command using shell */ - void exec_sh(const char* cmd) { + void exec_sh(const char* cmd, const vector>& env) { if (cmd != nullptr) { static const string shell{env_util::get("POLYBAR_SHELL", "/bin/sh")}; + + for (const auto& kv_pair : env) { + setenv(kv_pair.first.data(), kv_pair.second.data(), 1); + } + execlp(shell.c_str(), shell.c_str(), "-c", cmd, nullptr); throw system_error("execlp() failed"); } diff --git a/tests/unit_tests/utils/process.cpp b/tests/unit_tests/utils/process.cpp index 64ff21f6..a560382c 100644 --- a/tests/unit_tests/utils/process.cpp +++ b/tests/unit_tests/utils/process.cpp @@ -32,3 +32,13 @@ TEST(SpawnAsync, exit_code) { EXPECT_EQ(WEXITSTATUS(status), 42); } + +TEST(SpawnAsync, env) { + pid_t pid = spawn_async([] { exec_sh("exit $EXIT", {{"EXIT", "45"}}); }); + int status = 0; + pid_t res = waitpid(pid, &status, 0); + + EXPECT_EQ(res, pid); + + EXPECT_EQ(WEXITSTATUS(status), 45); +}