1 /**
2 * @file update_pidfile.c Functions for standalone daemons
3 */
4 #define _XOPEN_SOURCE 500 /* for getpgid */
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <stdio.h>
8 #include <unistd.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <errno.h>
12 #include <gm_msg.h>
13 #include "update_pidfile.h"
14
15 /**
16 * @fn void update_pidfile (const char *pname)
17 * @param argv0 name of this program
18 */
19 void
update_pidfile(char * pidfile)20 update_pidfile (char *pidfile)
21 {
22 long p;
23 pid_t pid;
24 mode_t prev_umask;
25 FILE *file;
26
27 /* make sure this program isn't already running. */
28 file = fopen (pidfile, "r");
29 if (file)
30 {
31 if (fscanf(file, "%ld", &p) == 1 && (pid = p) &&
32 (getpgid (pid) > -1))
33 {
34 if (pid != getpid())
35 {
36 err_msg("daemon already running: %s pid %ld\n", pidfile, p);
37 exit (1);
38 }
39 else
40 {
41 /* We have the same PID so were probably HUP'd */
42 return;
43 }
44 }
45 fclose (file);
46 }
47
48 /* write the pid of this process to the pidfile */
49 prev_umask = umask (0112);
50 unlink(pidfile);
51
52 file = fopen (pidfile, "w");
53 if (!file)
54 {
55 err_msg("Error writing pidfile '%s' -- %s\n",
56 pidfile, strerror (errno));
57 exit (1);
58 }
59 fprintf (file, "%ld\n", (long) getpid());
60 fclose (file);
61 umask (prev_umask);
62 }
63