Skip to content

Commit

Permalink
[485589] Close stdin etc. when daemonised.
Browse files Browse the repository at this point in the history
  • Loading branch information
ralight committed Feb 11, 2016
1 parent eb514c9 commit f588075
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 15 deletions.
1 change: 1 addition & 0 deletions ChangeLog.txt
Expand Up @@ -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,
Expand Down
46 changes: 31 additions & 15 deletions src/mosquitto.c
Expand Up @@ -21,6 +21,7 @@ and the Eclipse Distribution License is available at
# define _BSD_SOURCE
# include <unistd.h>
# include <grp.h>
# include <assert.h>
#endif

#ifndef WIN32
Expand Down Expand Up @@ -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)
{
Expand All @@ -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;
Expand Down Expand Up @@ -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){
Expand Down

0 comments on commit f588075

Please sign in to comment.