From d413151f5c0e3ccd3c7c7fe9d1db9112e7e83561 Mon Sep 17 00:00:00 2001 From: Eric Wong Date: Wed, 1 Jun 2016 03:06:55 +0000 Subject: stdin is always redirected to /dev/null There is no reason for stdin to ever be connected to a terminal, ensure we have a consistent stdin for iostat processes and the like. --- cmogstored.c | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/cmogstored.c b/cmogstored.c index ecfbd6e..5625775 100644 --- a/cmogstored.c +++ b/cmogstored.c @@ -152,12 +152,11 @@ static void dup2_null(int oldfd, int newfd, const char *errdest) die_errno("dup2(/dev/null,%s) failed", errdest); } -static void daemonize(void) +static void daemonize(int null_fd) { int ready_pipe[2]; pid_t pid; ssize_t r; - int fd; if (pipe(ready_pipe) < 0) die_errno("pipe() failed"); @@ -191,15 +190,9 @@ static void daemonize(void) if (chdir("/") < 0) die_errno("chdir(/) failed"); - fd = open("/dev/null", O_RDWR); - if (fd < 0) - die_errno("open(/dev/null) failed"); - - dup2_null(fd, STDIN_FILENO, "stdin"); - dup2_null(fd, STDOUT_FILENO, "stdout"); - dup2_null(fd, STDERR_FILENO, "stderr"); - mog_close(fd); + dup2_null(null_fd, STDOUT_FILENO, "stdout"); + dup2_null(null_fd, STDERR_FILENO, "stderr"); do { r = write(ready_pipe[1], &pid, sizeof(pid_t)); } while (r < 0 && errno == EINTR); @@ -239,6 +232,7 @@ MOG_NOINLINE static void setup(int argc, char *argv[]) { int pid_fd = -1; static struct argp argp = { options, parse_opt, NULL, summary }; + int null_fd; mog_mnt_refresh(); argp_parse(&argp, argc, argv, 0, NULL, &mog_cli); @@ -250,9 +244,16 @@ MOG_NOINLINE static void setup(int argc, char *argv[]) if (mog_cli.pidfile) pid_fd = mog_pidfile_prepare(mog_cli.pidfile); + null_fd = open("/dev/null", O_RDWR); + if (null_fd < 0) + die_errno("open(/dev/null) failed"); + dup2_null(null_fd, STDIN_FILENO, "stdin"); + /* don't daemonize if we're inheriting FDs, we're already daemonized */ if (mog_cli.daemonize && !getenv("CMOGSTORED_FD")) - daemonize(); + daemonize(null_fd); + + mog_close(null_fd); if (pid_fd >= 0 && mog_pidfile_commit(pid_fd) < 0) syslog(LOG_ERR, -- cgit v1.2.3-24-ge0c7