summaryrefslogtreecommitdiffstats
path: root/lib/libc
diff options
context:
space:
mode:
authorghelmer <ghelmer@FreeBSD.org>2003-11-10 22:01:42 +0000
committerghelmer <ghelmer@FreeBSD.org>2003-11-10 22:01:42 +0000
commitc5fcb1b2254d6529beea09a47bd70da6b98220f5 (patch)
tree0943c2b70e62ac5fe23f445330e4679ec07ddff1 /lib/libc
parent230f4975473b2bcb96199197e4ea9b0b5455abc0 (diff)
downloadFreeBSD-src-c5fcb1b2254d6529beea09a47bd70da6b98220f5.zip
FreeBSD-src-c5fcb1b2254d6529beea09a47bd70da6b98220f5.tar.gz
Prevent abnormal termination of a child daemon process when created
by a parent that is a session leader (e.g., login shell) by ignoring SIGHUP in before calling fork(2) and then restoring SIGHUP's action after setsid(3). Based on the patch by Martin Kammerhofer <mkamm@gmx.net>. PR: bin/25462 Reviewed by: bde, alex.neyman@auriga.ru
Diffstat (limited to 'lib/libc')
-rw-r--r--lib/libc/gen/daemon.317
-rw-r--r--lib/libc/gen/daemon.c21
2 files changed, 35 insertions, 3 deletions
diff --git a/lib/libc/gen/daemon.3 b/lib/libc/gen/daemon.3
index a08d0df..97025e6 100644
--- a/lib/libc/gen/daemon.3
+++ b/lib/libc/gen/daemon.3
@@ -71,12 +71,13 @@ The
function may fail and set
.Va errno
for any of the errors specified for the library functions
-.Xr fork 2
+.Xr fork 2 ,
and
.Xr setsid 2 .
.Sh SEE ALSO
.Xr fork 2 ,
-.Xr setsid 2
+.Xr setsid 2 ,
+.Xr sigaction 2
.Sh HISTORY
The
.Fn daemon
@@ -101,3 +102,15 @@ should therefore either call
.Fn daemon
before opening any files or sockets, or verify that any file
descriptors obtained have values greater than 2.
+.Pp
+The
+.Fn daemon
+function temporarily ignores
+.Dv SIGHUP
+while calling
+.Xr setsid 2
+to prevent a parent session group leader's calls to
+.Xr fork 2
+and then
+.Xr _exit 2
+from prematurely terminating the child process.
diff --git a/lib/libc/gen/daemon.c b/lib/libc/gen/daemon.c
index 315b827..0158976 100644
--- a/lib/libc/gen/daemon.c
+++ b/lib/libc/gen/daemon.c
@@ -38,8 +38,10 @@ static char sccsid[] = "@(#)daemon.c 8.1 (Berkeley) 6/4/93";
__FBSDID("$FreeBSD$");
#include "namespace.h"
+#include <errno.h>
#include <fcntl.h>
#include <paths.h>
+#include <signal.h>
#include <unistd.h>
#include "un-namespace.h"
@@ -47,7 +49,17 @@ int
daemon(nochdir, noclose)
int nochdir, noclose;
{
+ struct sigaction osa, sa;
int fd;
+ pid_t newgrp;
+ int oerrno;
+ int osa_ok;
+
+ /* A SIGHUP may be thrown when the parent exits below. */
+ sigemptyset(&sa.sa_mask);
+ sa.sa_handler = SIG_IGN;
+ sa.sa_flags = 0;
+ osa_ok = _sigaction(SIGHUP, &sa, &osa);
switch (fork()) {
case -1:
@@ -58,8 +70,15 @@ daemon(nochdir, noclose)
_exit(0);
}
- if (setsid() == -1)
+ newgrp = setsid();
+ oerrno = errno;
+ if (osa_ok != -1)
+ _sigaction(SIGHUP, &osa, NULL);
+
+ if (newgrp == -1) {
+ errno = oerrno;
return (-1);
+ }
if (!nochdir)
(void)chdir("/");
OpenPOWER on IntegriCloud