1 #include "pidfile.h"
2 
3 static volatile sig_atomic_t exit_requested = 0;
4 static const char *_pidfile = NULL;
5 
6 static void
pidfile_remove_file(void)7 pidfile_remove_file(void)
8 {
9     if (_pidfile != NULL) {
10         unlink(_pidfile);
11         _pidfile = NULL;
12     }
13 }
14 
15 static void
pidfile_atexit_handler(void)16 pidfile_atexit_handler(void)
17 {
18     pidfile_remove_file();
19 }
20 
21 static void
pidfile_sig_exit_handler(int sig)22 pidfile_sig_exit_handler(int sig)
23 {
24     (void)sig;
25     if (exit_requested)
26         return;
27     exit_requested = 1;
28     exit(0);
29 }
30 
31 static void
pidfile_install_signal_handlers(void (* handler)(int))32 pidfile_install_signal_handlers(void (*handler) (int))
33 {
34     signal(SIGPIPE, SIG_IGN);
35     signal(SIGALRM, handler);
36     signal(SIGHUP, handler);
37     signal(SIGINT, handler);
38     signal(SIGQUIT, handler);
39     signal(SIGTERM, handler);
40 #ifdef SIGXCPU
41     signal(SIGXCPU, handler);
42 #endif
43 }
44 
45 int
pidfile_create(const char * const pidfile)46 pidfile_create(const char *const pidfile)
47 {
48     FILE *fp;
49     _pidfile = pidfile;
50 
51     fp = fopen(pidfile, "w");
52     if (!fp) {
53         return -1;
54     }
55 
56     fprintf(fp, "%d\n", (int)getpid());
57     fclose(fp);
58 
59     pidfile_install_signal_handlers(pidfile_sig_exit_handler);
60     atexit(pidfile_atexit_handler);
61     return 0;
62 }
63