summaryrefslogtreecommitdiff
path: root/daemon.c
blob: 3cccedd15b0f0a817596f0d73ee6146dbd7f2427 (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
61
62
63
64
65
66
67
68
#include "conf.h"

#include <glib/gstdio.h>

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>

void daemonize() {
	gchar *pidfile = conf_get_string("audist", "pidfile");

	if(pidfile == NULL) {
		g_error("pidfile not set - can't daemonize");
	}

	FILE *f = fopen(pidfile, "w");
	if(f == NULL) {
		g_error("pidfile \"%s\" not writeable - can't daemonize", pidfile);
	}

	g_free(pidfile);

	switch(fork()) {
		case 0:
			break;
		case -1:
			g_error("fork() failed");
		default:
			_exit(0);
	}

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

void daemon_kill() {
	gchar *pidfile = conf_get_string("audist", "pidfile");

	if(pidfile == NULL) {
		g_error("pidfile not set");
	}

	FILE *f = fopen(pidfile, "r");
	g_free(pidfile);
	if(f == NULL) {
		g_error("can't read pidfile");
	}

	int pid;
	fscanf(f, "%d", &pid);
	fclose(f);

	kill(pid, SIGTERM);
}

void daemonize_finished() {
	gchar *pidfile = conf_get_string("audist", "pidfile");

	if(pidfile == NULL) {
		g_warning("pidfile not set");
		return;
	}

	g_unlink(pidfile);
	g_free(pidfile);
}