Add env parameter to exec_sh()

Before passing the cmd to exec() we set the required environment
variables.

Also add the test for it.
This commit is contained in:
TheDoctor314 2021-09-29 00:02:26 +05:30 committed by Patrick Ziegler
parent 1e0e50266b
commit a7b978412c
3 changed files with 17 additions and 2 deletions

View File

@ -16,7 +16,7 @@ namespace process_util {
void fork_detached(std::function<void()> const& lambda); void fork_detached(std::function<void()> const& lambda);
void exec(char* cmd, char** args); void exec(char* cmd, char** args);
void exec_sh(const char* cmd); void exec_sh(const char* cmd, const vector<pair<string, string>>& env = {});
int wait(pid_t pid); int wait(pid_t pid);

View File

@ -124,9 +124,14 @@ namespace process_util {
/** /**
* Execute command using shell * Execute command using shell
*/ */
void exec_sh(const char* cmd) { void exec_sh(const char* cmd, const vector<pair<string, string>>& env) {
if (cmd != nullptr) { if (cmd != nullptr) {
static const string shell{env_util::get("POLYBAR_SHELL", "/bin/sh")}; 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); execlp(shell.c_str(), shell.c_str(), "-c", cmd, nullptr);
throw system_error("execlp() failed"); throw system_error("execlp() failed");
} }

View File

@ -32,3 +32,13 @@ TEST(SpawnAsync, exit_code) {
EXPECT_EQ(WEXITSTATUS(status), 42); 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);
}