[go: up one dir, main page]

File: daemon.c

package info (click to toggle)
cctools 9.9-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 44,624 kB
  • sloc: ansic: 192,539; python: 20,827; cpp: 20,199; sh: 11,719; perl: 4,106; xml: 3,688; makefile: 1,224
file content (81 lines) | stat: -rw-r--r-- 1,809 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
74
75
76
77
78
79
80
81
/*
 * Copyright (C) 2011- The University of Notre Dame
 * This software is distributed under the GNU General Public License.
 * See the file COPYING for details.
*/

#include "daemon.h"

#include "debug.h"
#include "fd.h"

#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void daemonize (int cdroot, const char *pidfile)
{
	/* Become session leader and lose controlling terminal */
	pid_t pid = fork();
	if (pid < 0) {
		fatal("could not fork: %s", strerror(errno));
	} else if (pid > 0) {
		exit(EXIT_SUCCESS); /* exit parent */
	}

	pid_t group = setsid();
	if (group == (pid_t) -1) {
		fatal("could not create session: %s", strerror(errno));
	}

	/* Second fork ensures process cannot acquire controlling terminal */
	pid = fork();
	if (pid < 0) {
		fatal("could not fork: %s", strerror(errno));
	} else if (pid > 0) {
		exit(EXIT_SUCCESS); /* exit parent */
	}

	if (pidfile && strlen(pidfile)) {
		FILE *file = fopen(pidfile, "w");
		if (file) {
			fprintf(file, "%ld", (long)getpid());
			fclose(file);
		} else {
			fatal("could not open `%s' for writing: %s", pidfile, strerror(errno));
		}
	}

	if (cdroot){
		int status = chdir("/");
		if (status == -1) {
			fatal("could not chdir to `/': %s", strerror(errno));
		}
	}

	umask(0);

	fd_nonstd_close();

	FILE *file0 = freopen("/dev/null", "r", stdin);
	if (file0 == NULL) {
		fatal("could not reopen stdin: %s", strerror(errno));
	}
	FILE *file1 = freopen("/dev/null", "w", stdout);
	if (file1 == NULL) {
		fatal("could not reopen stdout: %s", strerror(errno));
	}
	FILE *file2 = freopen("/dev/null", "w", stderr);
	if (file2 == NULL) {
		fatal("could not reopen stderr: %s", strerror(errno));
	}

	debug_reopen();
}

/* vim: set noexpandtab tabstop=4: */