Skip to content

Commit 89f9d98

Browse files
util: Redirect stdin, stdout and stderr to '/dev/null' in case of daemonize
Signed-off-by: Yuichiro NAITO <[email protected]>
1 parent 10ebd3a commit 89f9d98

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/flb_utils.c

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@
2222
#include <string.h>
2323
#include <time.h>
2424
#include <ctype.h>
25+
#ifdef FLB_HAVE_FORK
26+
#include <fcntl.h>
27+
#include <unistd.h>
28+
#endif
2529

2630
#include <sys/types.h>
2731
#include <sys/stat.h>
@@ -177,6 +181,7 @@ void flb_utils_warn_c(const char *msg)
177181
/* Run current process in background mode */
178182
int flb_utils_set_daemon(struct flb_config *config)
179183
{
184+
int fd;
180185
pid_t pid;
181186

182187
if ((pid = fork()) < 0){
@@ -202,8 +207,24 @@ int flb_utils_set_daemon(struct flb_config *config)
202207
/* Our last STDOUT messages */
203208
flb_info("switching to background mode (PID=%ld)", (long) getpid());
204209

205-
fclose(stderr);
206-
fclose(stdout);
210+
/* Redirect stdin, stdout, stderr to `/dev/null`. */
211+
fd = open("/dev/null", O_RDWR);
212+
if (fd == -1) {
213+
flb_error("Failed to open /dev/null for daemonization");
214+
return -1;
215+
}
216+
217+
if (dup2(fd, STDIN_FILENO) == -1 ||
218+
dup2(fd, STDOUT_FILENO) == -1 ||
219+
dup2(fd, STDERR_FILENO) == -1) {
220+
close(fd);
221+
flb_error("Failed to redirect standard file descriptors to /dev/null");
222+
return -1;
223+
}
224+
225+
if (fd > 2) {
226+
close(fd);
227+
}
207228

208229
return 0;
209230
}

0 commit comments

Comments
 (0)