2018-08-18 15:54:20 +00:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <sys/wait.h>
|
2019-01-08 20:05:44 +00:00
|
|
|
#include <giomm.h>
|
2018-12-26 10:13:36 +00:00
|
|
|
#include <unistd.h>
|
2018-08-18 15:54:20 +00:00
|
|
|
|
|
|
|
namespace waybar::util::command {
|
|
|
|
|
2018-09-05 17:20:19 +00:00
|
|
|
struct res {
|
2018-08-18 15:54:20 +00:00
|
|
|
int exit_code;
|
|
|
|
std::string out;
|
|
|
|
};
|
|
|
|
|
2018-09-05 17:20:19 +00:00
|
|
|
inline struct res exec(const std::string cmd)
|
2018-08-18 15:54:20 +00:00
|
|
|
{
|
|
|
|
FILE* fp(popen(cmd.c_str(), "r"));
|
|
|
|
if (!fp) {
|
|
|
|
return { -1, "" };
|
|
|
|
}
|
|
|
|
|
|
|
|
std::array<char, 128> buffer = {0};
|
|
|
|
std::string output;
|
|
|
|
while (feof(fp) == 0) {
|
|
|
|
if (fgets(buffer.data(), 128, fp) != nullptr) {
|
|
|
|
output += buffer.data();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove last newline
|
|
|
|
if (!output.empty() && output[output.length()-1] == '\n') {
|
|
|
|
output.erase(output.length()-1);
|
|
|
|
}
|
|
|
|
int exit_code = WEXITSTATUS(pclose(fp));
|
2018-10-29 17:04:09 +00:00
|
|
|
return {exit_code, output};
|
2018-08-18 15:54:20 +00:00
|
|
|
}
|
|
|
|
|
2018-10-29 17:04:09 +00:00
|
|
|
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;
|
2018-08-18 15:54:20 +00:00
|
|
|
}
|
2018-10-29 17:04:09 +00:00
|
|
|
|
|
|
|
} // namespace waybar::util::command
|