diff --git a/src/flb_utils.c b/src/flb_utils.c index 659411619ee..2e34467d04c 100644 --- a/src/flb_utils.c +++ b/src/flb_utils.c @@ -22,6 +22,10 @@ #include #include #include +#ifdef FLB_HAVE_FORK +#include +#include +#endif #include #include @@ -177,6 +181,7 @@ void flb_utils_warn_c(const char *msg) /* Run current process in background mode */ int flb_utils_set_daemon(struct flb_config *config) { + int fd; pid_t pid; if ((pid = fork()) < 0){ @@ -202,8 +207,24 @@ int flb_utils_set_daemon(struct flb_config *config) /* Our last STDOUT messages */ flb_info("switching to background mode (PID=%ld)", (long) getpid()); - fclose(stderr); - fclose(stdout); + /* Redirect stdin, stdout, stderr to `/dev/null`. */ + fd = open("/dev/null", O_RDWR); + if (fd == -1) { + flb_error("Failed to open /dev/null for daemonization"); + return -1; + } + + if (dup2(fd, STDIN_FILENO) == -1 || + dup2(fd, STDOUT_FILENO) == -1 || + dup2(fd, STDERR_FILENO) == -1) { + close(fd); + flb_error("Failed to redirect standard file descriptors to /dev/null"); + return -1; + } + + if (fd > 2) { + close(fd); + } return 0; }