-
Notifications
You must be signed in to change notification settings - Fork 1
/
pid_file.c
122 lines (98 loc) · 2.12 KB
/
pid_file.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#if HAVE_ERRNO_H
# include <errno.h>
#endif
#if HAVE_SIGNAL_H
# include <signal.h>
#endif
#include <error.h>
#include <dprintf.h>
int pid_file_create(char *pid_file)
{
#if HAVE_GETPID
char buf[64];
FILE* fp = NULL;
pid_t mypid;
pid_t otherpid = -1;
#if HAVE_SETEUID && HAVE_SETEGID
gid_t oldegid = -1;
uid_t oldeuid = -1;
#endif
#if HAVE_SETEUID && HAVE_SETEGID
oldegid = getegid();
oldeuid = geteuid();
setegid(getgid());
seteuid(getuid());
#endif
// check if the pid file exists
if((fp=fopen(pid_file, "r")) != NULL)
{
// if the pid file exists what does it say?
if(fgets(buf, sizeof(buf), fp) == NULL)
{
fprintf(stderr, "error reading pid file: %s (%s)\n", pid_file, error_string);
goto ERR;
}
fclose(fp);
otherpid = atoi(buf);
// check to see if the pid is valid
if(kill(otherpid, 0) == 0)
{
// if it is alive then we quit
fprintf(stderr, "there is another program already running with pid %d.\n", (int)otherpid);
goto ERR;
}
}
// create the pid file
if((fp=fopen(pid_file, "w")) == NULL)
{
fprintf(stderr, "could not create pid file: %s (%s)\n", pid_file, error_string);
goto ERR;
}
mypid = getpid();
fprintf(fp, "%d\n", (int)mypid);
fclose(fp);
dprintf((stderr, "pid file %s successfully created with value %d.\n",
pid_file, (int)mypid));
#if HAVE_SETEUID && HAVE_SETEGID
setegid(oldegid);
seteuid(oldeuid);
#endif
return 0;
ERR:
if(fp) { fclose(fp); fp = NULL; }
#if HAVE_SETEUID && HAVE_SETEGID
setegid(oldegid);
seteuid(oldeuid);
#endif
return(-1);
#else
return(-1);
#endif
}
int pid_file_delete(char *pid_file)
{
int ret;
#if HAVE_SETEUID && HAVE_SETEGID
gid_t oldegid = -1;
uid_t oldeuid = -1;
#endif
#if HAVE_SETEUID && HAVE_SETEGID
oldegid = getegid();
oldeuid = geteuid();
setegid(getgid());
seteuid(getuid());
#endif
ret = unlink(pid_file);
#if HAVE_SETEUID && HAVE_SETEGID
setegid(oldegid);
seteuid(oldeuid);
#endif
return ret;
}