File: daemonize.c

package info (click to toggle)
dhcp-probe 1.3.0-10.1
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, buster, jessie, jessie-kfreebsd, sid, stretch, trixie
  • size: 1,312 kB
  • ctags: 250
  • sloc: sh: 4,294; ansic: 2,305; perl: 279; makefile: 98
file content (73 lines) | stat: -rw-r--r-- 1,564 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* Daemonize correctly.

   Based closely on daemon_init() from
   "UNIX Network Programming: Volume 1", Second Edition,
   by W. Richard Stevens.  That sample code is available via
   ftp://ftp.kohala.com/pub/rstevens/unpv12e.tar.gz.
*/


#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "defs.h"

#include "daemonize.h"
#include "report.h"
#include "open_max.h"


void
daemonize(void)
{
	int i;
	pid_t pid;
	struct sigaction sa;

	if ((pid = fork()) < 0) {
		report(LOG_ERR, "fork: %s", get_errmsg());
		report(LOG_NOTICE, "exiting");
		exit(1);
	} else if (pid != 0)
		exit(0); /* parent terminates */

	/* first child continues */

	setsid();	/* become a session leader */
		
	/* ignore HUP we will receive when session leader (first child) terminates */
	sigemptyset(&sa.sa_mask);
	sa.sa_handler = SIG_IGN;
	if (sigaction(SIGHUP, &sa, NULL) < 0) {
		report(LOG_ERR, "sigaction: %s", get_errmsg());
		report(LOG_NOTICE, "exiting");
		exit(1);
	}

	if ((pid = fork()) < 0) {
		report(LOG_ERR, "fork: %s", get_errmsg());
		report(LOG_NOTICE, "exiting");
		exit(1);
	} else if (pid != 0)
		exit(0); /* first child terminates */

	/* second child continues */

	/* We take care of the chdir in the main program
	chdir("/");
	*/

	/* We'll allow ourself to inherit the file mode creation mask
	umask(0);
	*/

	/* Close inherited descriptors.
	   There is no portable way to determine what descriptors were inherited.
	   so we'll instead try to close all descriptors up to some maximum value.
	*/
	for (i = 0; i < open_max(); i++)
		close(i);

	return;
}