summaryrefslogtreecommitdiff
path: root/libdaemon
diff options
context:
space:
mode:
authorZdenek Kabelac <zkabelac@redhat.com>2017-08-25 11:55:38 +0200
committerZdenek Kabelac <zkabelac@redhat.com>2017-08-25 14:20:57 +0200
commitb3b1e788e16c77f6784f30b8e984f68792f8fa1a (patch)
treec878f262bd6d5921373d6e83747947e247283a68 /libdaemon
parent5de944420224f3b629e843f9c190132ed9ff3dca (diff)
downloadlvm2-b3b1e788e16c77f6784f30b8e984f68792f8fa1a.tar.gz
daemonize: more unified code
ATM we have several instances of daemonizing code. Each has its 'special' logic so not completely easy to unify them all into a single routine. Start to unify them and use one strategy for rediricting all input/outpus to /dev/null - use 'dup2' function for this and open /dev/null before fork to make sure it's available.
Diffstat (limited to 'libdaemon')
-rw-r--r--libdaemon/server/daemon-server.c21
1 files changed, 15 insertions, 6 deletions
diff --git a/libdaemon/server/daemon-server.c b/libdaemon/server/daemon-server.c
index 6fdf195c7..0950c2e16 100644
--- a/libdaemon/server/daemon-server.c
+++ b/libdaemon/server/daemon-server.c
@@ -334,6 +334,11 @@ static void _daemonise(daemon_state s)
struct timeval tval;
sigset_t my_sigset;
+ if ((fd = open("/dev/null", O_RDWR)) == -1) {
+ fprintf(stderr, "Unable to open /dev/null.\n");
+ exit(EXIT_FAILURE);
+ }
+
sigemptyset(&my_sigset);
if (sigprocmask(SIG_SETMASK, &my_sigset, NULL) < 0) {
fprintf(stderr, "Unable to restore signals.\n");
@@ -350,6 +355,7 @@ static void _daemonise(daemon_state s)
break;
default:
+ (void) close(fd);
/* Wait for response from child */
while (!waitpid(pid, &child_status, WNOHANG) && !_shutdown_requested) {
tval.tv_sec = 0;
@@ -374,12 +380,20 @@ static void _daemonise(daemon_state s)
if (chdir("/"))
exit(1);
+ (void) dup2(fd, STDIN_FILENO);
+ (void) dup2(fd, STDOUT_FILENO);
+ (void) dup2(fd, STDERR_FILENO);
+
+ if (fd > STDERR_FILENO)
+ (void) close(fd);
+
+ /* Switch to sysconf(_SC_OPEN_MAX) ?? */
if (getrlimit(RLIMIT_NOFILE, &rlim) < 0)
fd = 256; /* just have to guess */
else
fd = rlim.rlim_cur;
- for (--fd; fd >= 0; fd--) {
+ for (--fd; fd > STDERR_FILENO; fd--) {
#ifdef __linux__
/* Do not close fds preloaded by systemd! */
if (_systemd_activation && fd == SD_FD_SOCKET_SERVER)
@@ -388,11 +402,6 @@ static void _daemonise(daemon_state s)
(void) close(fd);
}
- if ((open("/dev/null", O_RDONLY) < 0) ||
- (open("/dev/null", O_WRONLY) < 0) ||
- (open("/dev/null", O_WRONLY) < 0))
- exit(1);
-
setsid();
}