-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpidfile.c
51 lines (43 loc) · 829 Bytes
/
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
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
int
pidfile(const char *file)
{
int fd;
int flags;
int pidlen;
char pid[32];
struct flock lock;
fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
return -1;
}
flags = fcntl(fd, F_GETFD);
if (flags == -1) {
return -1;
}
flags |= FD_CLOEXEC;
if (fcntl(fd, F_SETFD, flags) == -1) {
return -1;
}
/* lock file */
lock.l_len = 0;
lock.l_start = 0;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLK, &lock) == -1) {
return -1;
}
if (ftruncate(fd, 0) == -1) {
return -1;
}
pidlen = snprintf(pid, sizeof(pid), "%ld\n", (long)getpid());
if (write(fd, pid, pidlen) != pidlen) {
return -1;
}
return fd;
}