waybar/include/util/command.hpp

53 lines
1.0 KiB
C++
Raw Normal View History

#pragma once
#include <giomm.h>
2019-04-18 17:52:00 +02:00
#include <sys/wait.h>
2018-12-26 11:13:36 +01:00
#include <unistd.h>
namespace waybar::util::command {
struct res {
2019-04-18 17:52:00 +02:00
int exit_code;
std::string out;
};
2019-04-18 17:52:00 +02:00
inline struct res exec(const std::string cmd) {
FILE* fp(popen(cmd.c_str(), "r"));
if (!fp) {
2019-04-18 17:52:00 +02:00
return {-1, ""};
}
std::array<char, 128> buffer = {0};
2019-04-18 17:52:00 +02:00
std::string output;
while (feof(fp) == 0) {
if (fgets(buffer.data(), 128, fp) != nullptr) {
output += buffer.data();
}
}
// Remove last newline
2019-04-18 17:52:00 +02:00
if (!output.empty() && output[output.length() - 1] == '\n') {
output.erase(output.length() - 1);
}
int exit_code = WEXITSTATUS(pclose(fp));
return {exit_code, output};
}
inline bool forkExec(std::string cmd) {
if (cmd == "") return true;
int32_t pid = fork();
if (pid < 0) {
printf("Unable to exec cmd %s, error %s", cmd.c_str(), strerror(errno));
return false;
}
// Child executes the command
if (!pid) execl("/bin/sh", "sh", "-c", cmd.c_str(), (char*)0);
return true;
}
} // namespace waybar::util::command