summaryrefslogtreecommitdiff
path: root/tacplus-daemon/daemon.c
blob: 0f1e2e47f16aec0d7e9f588b343a0d3644b82417 (plain)
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
/*
	TACACS+ D-Bus Daemon code

	Copyright (c) 2019 AT&T Intellectual Property.
	Copyright (c) 2015-2016 Brocade Communications Systems, Inc.

	SPDX-License-Identifier: GPL-2.0-only
*/

#include "daemon.h"

/* TODO
 * -use strerror_r() instead of strerror()
 */


/* TODO: Take filename from command line */
static void record_pid(const char *fname)
{
	FILE *f = fopen(fname, "w");

	if (f == NULL) {
		/* TODO: append strerr() */
		syslog(LOG_ERR, "Failed to open pid file: %s", fname);
		return;
	}

	fprintf(f, "%u\n", getpid());
	fclose(f);
}

void daemonize(const char *tacplus_pid)
{
	/* 0 returned in child */
	if (fork() != 0) {
		exit(EXIT_SUCCESS); /* parent exit */
	}

	/* Become new process group leader */
	if (setsid() < 0) {
		fprintf(stderr, "setsid() failed. Error: %s", strerror(errno));
		exit(EXIT_FAILURE);
	}

	/* Overwrite parent's cwd */
	if(chdir("/") < 0) {
		fprintf(stderr, "Changing cwd to root directory failed. Error: %s",
						   strerror(errno));
		exit(EXIT_FAILURE);
	}
	/* Close standard file descriptors */
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	/* Reset file permissions */
	umask(0);
	record_pid(tacplus_pid);
}