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
This commit is contained in:
parent
2c85cbd9b5
commit
8b2b22e84d
@ -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.
|
||||
|
@ -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("/");
|
||||
|
Loading…
Reference in New Issue
Block a user