Skip to content

Commit 2852fd4

Browse files
lib: monkey: Redirect std{in|out|err} to '/dev/null' in case of daemonize.
Signed-off-by: Yuichiro NAITO <[email protected]>
1 parent 705b15c commit 2852fd4

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

lib/monkey/mk_core/mk_utils.c

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@
2828
#include <sys/types.h>
2929
#include <sys/stat.h>
3030
#include <fcntl.h>
31+
#ifndef _WIN32
32+
#include <unistd.h>
33+
#endif
3134
#include <mk_core/mk_utils.h>
3235

3336
#include <mk_core/mk_unistd.h>
@@ -293,6 +296,7 @@ int mk_utils_worker_spawn(void (*func) (void *), void *arg, pthread_t *tid)
293296
/* Run current process in background mode (daemon, evil Monkey >:) */
294297
int mk_utils_set_daemon()
295298
{
299+
int fd;
296300
pid_t pid;
297301

298302
if ((pid = fork()) < 0) {
@@ -318,8 +322,15 @@ int mk_utils_set_daemon()
318322
/* Our last STDOUT messages */
319323
mk_info("Background mode ON");
320324

321-
fclose(stderr);
322-
fclose(stdout);
325+
/* Redirect stdin, stdout, stderr to `/dev/null`. */
326+
fd = open("/dev/null", O_RDWR);
327+
if (fd != -1) {
328+
dup2(fd, STDIN_FILENO);
329+
dup2(fd, STDOUT_FILENO);
330+
dup2(fd, STDERR_FILENO);
331+
if (fd > 2)
332+
close(fd);
333+
}
323334

324335
return 0;
325336
}

0 commit comments

Comments
 (0)