Add error checks and fork() call after setsid()

In order to start a daemon, a second call for fork() after changing
session ID is usually required, in order to prevent acquiring a
controlling tty when it eventually writes to one.
This commit is contained in:
Petar Kapris 2020-12-06 19:51:37 +01:00
parent e4c67052ef
commit 06c238d486

View file

@ -340,13 +340,37 @@ char *argv[];
}
/* If running in daemon mode (no parameters) */
if (fork()) /* the parent process */
exit(0); /* exits */
pid_t pid;
if ((pid = fork()) < 0) {
openlog("timeoutd", OPENLOG_FLAGS, LOG_DAEMON);
syslog(LOG_ERR, "Failed to execute fork number 1");
closelog();
exit(1);
}
if (pid > 0)
exit(0);
close(0);
close(1);
close(2);
setsid();
if (setsid() < 0) {
openlog("timeoutd", OPENLOG_FLAGS, LOG_DAEMON);
syslog(LOG_ERR, "Failed to set new session ID at startup.");
closelog();
exit(1);
}
if ((pid = fork()) < 0) {
openlog("timeoutd", OPENLOG_FLAGS, LOG_DAEMON);
syslog(LOG_ERR, "Failed to execute fork number 2");
closelog();
exit(1);
}
if (pid > 0)
exit(0);
umask(0);
openlog("timeoutd", OPENLOG_FLAGS, LOG_DAEMON);
syslog(LOG_NOTICE, "Daemon started.");