Redirect process output to dev null

This commit is contained in:
Jérôme BOULMIER 2020-05-06 22:28:05 +02:00 committed by Patrick Ziegler
parent e9d2f022cd
commit f016b99e08
3 changed files with 20 additions and 2 deletions

View File

@ -8,6 +8,8 @@ namespace process_util {
bool in_parent_process(pid_t pid); bool in_parent_process(pid_t pid);
bool in_forked_process(pid_t pid); bool in_forked_process(pid_t pid);
void redirect_process_output_to_dev_null();
void exec(char* cmd, char** args); void exec(char* cmd, char** args);
void exec_sh(const char* cmd); void exec_sh(const char* cmd);

View File

@ -37,6 +37,7 @@ int command<output_policy::IGNORED>::exec(bool wait_for_completion) {
if (process_util::in_forked_process(m_forkpid)) { if (process_util::in_forked_process(m_forkpid)) {
setpgid(m_forkpid, 0); setpgid(m_forkpid, 0);
process_util::redirect_process_output_to_dev_null();
process_util::exec_sh(m_cmd.c_str()); process_util::exec_sh(m_cmd.c_str());
} else { } else {
if (wait_for_completion) { if (wait_for_completion) {

View File

@ -1,9 +1,11 @@
#include "utils/process.hpp"
#include <fcntl.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <unistd.h> #include <unistd.h>
#include "errors.hpp" #include "errors.hpp"
#include "utils/env.hpp" #include "utils/env.hpp"
#include "utils/process.hpp"
#include "utils/string.hpp" #include "utils/string.hpp"
POLYBAR_NS POLYBAR_NS
@ -23,6 +25,19 @@ namespace process_util {
return pid == 0; return pid == 0;
} }
void redirect_process_output_to_dev_null() {
auto redirect = [](int fd_to_redirect) {
int fd = open("/dev/null", O_WRONLY);
if (fd < 0 || dup2(fd, fd_to_redirect) < 0) {
throw system_error("Failed to redirect process output");
}
close(fd);
};
redirect(STDOUT_FILENO);
redirect(STDERR_FILENO);
}
/** /**
* Execute command * Execute command
*/ */
@ -105,6 +120,6 @@ namespace process_util {
bool notify_childprocess() { bool notify_childprocess() {
return wait_for_completion_nohang() > 0; return wait_for_completion_nohang() > 0;
} }
} } // namespace process_util
POLYBAR_NS_END POLYBAR_NS_END