-
Notifications
You must be signed in to change notification settings - Fork 36
/
pidfile.c
60 lines (48 loc) · 1.3 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
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include "chaosvpn.h"
bool
pidfile_create_pidfile(const char *filename)
{
char lockfile[512];
int fh_lockfile;
FILE *handle_pidfile;
bool retval = false;
snprintf(lockfile, sizeof(lockfile), "%s.lck", filename);
fh_lockfile = open(lockfile, O_CREAT | O_EXCL, 0600);
if (fh_lockfile == -1) {
log_info("create_pidfile: lockfile '%s' already exists.", lockfile);
goto out;
}
close(fh_lockfile);
handle_pidfile = fopen(filename, "w");
if (!handle_pidfile) {
log_err("create_pidfile: error creating pidfile: %s", strerror(errno));
goto out_unlock;
}
if (fprintf(handle_pidfile, "%d\n", getpid()) < 0) {
log_err("create_pidfile: error writing to pidfile: %s", strerror(errno));
goto out_close;
}
if (fclose(handle_pidfile) != 0) {
log_err("create_pidfile: error writing to pidfile: %s", strerror(errno));
goto out_unlock;
}
if (chmod(filename, 0600) != 0) {
log_warn("create_pidfile: error chmod pidfile: %s", strerror(errno));
}
retval = true;
goto out_unlock;
out_close:
fclose(handle_pidfile);
out_unlock:
if (unlink(lockfile)) {
log_warn("create_pidfile: warning: couldn't remove lockfile '%s': %s", lockfile, strerror(errno));
}
out:
return retval;
}