From f5880759311eb4a690239d1a1f51aae5e8886efd Mon Sep 17 00:00:00 2001 From: "Roger A. Light" Date: Thu, 11 Feb 2016 21:49:55 +0000 Subject: [PATCH] [485589] Close stdin etc. when daemonised. Bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=485589 --- ChangeLog.txt | 1 + src/mosquitto.c | 46 +++++++++++++++++++++++++++++++--------------- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/ChangeLog.txt b/ChangeLog.txt index 19ddebd4f3..ab0d7d0f5b 100644 --- a/ChangeLog.txt +++ b/ChangeLog.txt @@ -5,6 +5,7 @@ Broker: mount point. This is only affects brokers where the mount_point option is in use. Closes #487178. - Fix detection of broken connections on Windows. Closes #485143. +- Close stdin etc. when daemonised. Closes #485589. Client library: - mosq->want_write should be cleared immediately before a call to SSL_write, diff --git a/src/mosquitto.c b/src/mosquitto.c index eaf439535e..55ff678ca5 100644 --- a/src/mosquitto.c +++ b/src/mosquitto.c @@ -21,6 +21,7 @@ and the Eclipse Distribution License is available at # define _BSD_SOURCE # include # include +# include #endif #ifndef WIN32 @@ -175,6 +176,35 @@ void handle_sigusr1(int signal) #endif } +void mosquitto__daemonise(void) +{ +#ifndef WIN32 + char err[256]; + pid_t pid; + + pid = fork(); + if(pid < 0){ + strerror_r(errno, err, 256); + _mosquitto_log_printf(NULL, MOSQ_LOG_ERR, "Error in fork: %s", err); + exit(1); + } + if(pid > 0){ + exit(0); + } + if(setsid() < 0){ + strerror_r(errno, err, 256); + _mosquitto_log_printf(NULL, MOSQ_LOG_ERR, "Error in setsid: %s", err); + exit(1); + } + + assert(freopen("/dev/null", "r", stdin)); + assert(freopen("/dev/null", "w", stdout)); + assert(freopen("/dev/null", "w", stderr)); +#else + _mosquitto_log_printf(NULL, MOSQ_LOG_WARNING, "Warning: Can't start in daemon mode in Windows."); +#endif +} + /* Signal handler for SIGUSR2 - vacuum the db. */ void handle_sigusr2(int signal) { @@ -197,7 +227,6 @@ int main(int argc, char *argv[]) #ifdef WIN32 SYSTEMTIME st; #else - char err[256]; struct timeval tv; #endif struct mosquitto *ctxt, *ctxt_tmp; @@ -236,20 +265,7 @@ int main(int argc, char *argv[]) int_db.config = &config; if(config.daemon){ -#ifndef WIN32 - switch(fork()){ - case 0: - break; - case -1: - strerror_r(errno, err, 256); - _mosquitto_log_printf(NULL, MOSQ_LOG_ERR, "Error in fork: %s", err); - return 1; - default: - return MOSQ_ERR_SUCCESS; - } -#else - _mosquitto_log_printf(NULL, MOSQ_LOG_WARNING, "Warning: Can't start in daemon mode in Windows."); -#endif + mosquitto__daemonise(); } if(config.daemon && config.pid_file){