os: add setEnv to process

This commit is contained in:
Vaxry 2024-11-15 20:28:59 +00:00
parent 315fba5d21
commit e74177e025
3 changed files with 17 additions and 3 deletions

View file

@ -2,6 +2,7 @@
#include <string>
#include <vector>
#include <utility>
namespace Hyprutils {
namespace OS {
@ -10,6 +11,8 @@ namespace Hyprutils {
/* Creates a process object, doesn't run yet */
CProcess(const std::string& binary_, const std::vector<std::string>& args_);
void addEnv(const std::string& name, const std::string& value);
/* Run the process, synchronously, get the stdout and stderr. False on fail */
bool runSync();
@ -21,8 +24,9 @@ namespace Hyprutils {
const std::string& stdErr();
private:
std::string binary, out, err;
std::vector<std::string> args;
std::string binary, out, err;
std::vector<std::string> args;
std::vector<std::pair<std::string, std::string>> env;
};
}
}

View file

@ -16,6 +16,10 @@ Hyprutils::OS::CProcess::CProcess(const std::string& binary_, const std::vector<
;
}
void Hyprutils::OS::CProcess::addEnv(const std::string& name, const std::string& value) {
env.emplace_back(std::make_pair<>(name, value));
}
bool Hyprutils::OS::CProcess::runSync() {
int outPipe[2], errPipe[2];
if (pipe(outPipe))
@ -53,6 +57,11 @@ bool Hyprutils::OS::CProcess::runSync() {
argsC.emplace_back(nullptr);
// pass env
for (auto& [n, v] : env) {
setenv(n.c_str(), v.c_str(), 1);
}
execvp(binary.c_str(), (char* const*)argsC.data());
exit(1);
} else {

View file

@ -6,7 +6,8 @@ using namespace Hyprutils::OS;
int main(int argc, char** argv, char** envp) {
int ret = 0;
CProcess process("echo", {"Hello World!"});
CProcess process("sh", {"-c", "echo \"Hello $WORLD!\""});
process.addEnv("WORLD", "World");
EXPECT(process.runAsync(), true);
EXPECT(process.runSync(), true);