-
Notifications
You must be signed in to change notification settings - Fork 74
/
pidfile.c
62 lines (53 loc) · 1.06 KB
/
pidfile.c
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
#include "pidfile.h"
static volatile sig_atomic_t exit_requested = 0;
static const char *_pidfile = NULL;
static void
pidfile_remove_file(void)
{
if (_pidfile != NULL) {
unlink(_pidfile);
_pidfile = NULL;
}
}
static void
pidfile_atexit_handler(void)
{
pidfile_remove_file();
}
static void
pidfile_sig_exit_handler(int sig)
{
(void)sig;
if (exit_requested)
return;
exit_requested = 1;
exit(0);
}
static void
pidfile_install_signal_handlers(void (*handler) (int))
{
signal(SIGPIPE, SIG_IGN);
signal(SIGALRM, handler);
signal(SIGHUP, handler);
signal(SIGINT, handler);
signal(SIGQUIT, handler);
signal(SIGTERM, handler);
#ifdef SIGXCPU
signal(SIGXCPU, handler);
#endif
}
int
pidfile_create(const char *const pidfile)
{
FILE *fp;
_pidfile = pidfile;
fp = fopen(pidfile, "w");
if (!fp) {
return -1;
}
fprintf(fp, "%d\n", (int)getpid());
fclose(fp);
pidfile_install_signal_handlers(pidfile_sig_exit_handler);
atexit(pidfile_atexit_handler);
return 0;
}