|
| 1 | +#include <stdio.h> |
| 2 | +#include <errno.h> |
| 3 | +#include <string.h> |
| 4 | +#include <unistd.h> |
| 5 | +#include <fcntl.h> |
| 6 | +#include <sys/wait.h> |
| 7 | + |
| 8 | +#define BUF_SIZE 64 |
| 9 | + |
| 10 | +static int pid_fd = -1; |
| 11 | + |
| 12 | +void ocre_pid_file_release(void) |
| 13 | +{ |
| 14 | + /* TODO: should we release the flock? */ |
| 15 | + |
| 16 | + if (pid_fd >= 0) { |
| 17 | + close(pid_fd); |
| 18 | + pid_fd = -1; |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +int ocre_pid_file_manage(const char *pid_file) |
| 23 | +{ |
| 24 | + int ret = -1; |
| 25 | + |
| 26 | + pid_fd = open(pid_file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); |
| 27 | + if (pid_fd < 0) { |
| 28 | + fprintf(stderr, "Failed to open PID file '%s': %s\n", pid_file, strerror(errno)); |
| 29 | + return -1; |
| 30 | + } |
| 31 | + |
| 32 | + /* TODO: should we really set CLOEXEC? */ |
| 33 | + |
| 34 | + int flags = fcntl(pid_fd, F_GETFD); |
| 35 | + if (flags < 0) { |
| 36 | + fprintf(stderr, "Failed to get flags for PID file '%s': %s\n", pid_file, strerror(errno)); |
| 37 | + goto finish; |
| 38 | + } |
| 39 | + |
| 40 | + flags |= FD_CLOEXEC; |
| 41 | + |
| 42 | + if (fcntl(pid_fd, F_SETFD, flags) < 0) { |
| 43 | + fprintf(stderr, "Failed to set flags for PID file '%s': %s\n", pid_file, strerror(errno)); |
| 44 | + goto finish; |
| 45 | + } |
| 46 | + |
| 47 | + /* TODO: maybe check if the process is running? */ |
| 48 | + |
| 49 | + /* TODO: do we need the flock? */ |
| 50 | + |
| 51 | + struct flock fl = { |
| 52 | + .l_type = F_WRLCK, |
| 53 | + .l_whence = SEEK_SET, |
| 54 | + .l_start = 0, |
| 55 | + .l_len = 0, |
| 56 | + }; |
| 57 | + |
| 58 | + if (fcntl(pid_fd, F_WRLCK, &fl) < 0) { |
| 59 | + fprintf(stderr, "Failed to lock PID file '%s': %s\n", pid_file, strerror(errno)); |
| 60 | + goto finish; |
| 61 | + } |
| 62 | + |
| 63 | + if (ftruncate(pid_fd, 0) < 0) { |
| 64 | + fprintf(stderr, "Failed to truncate PID file '%s': %s\n", pid_file, strerror(errno)); |
| 65 | + goto finish; |
| 66 | + } |
| 67 | + |
| 68 | + char buf[BUF_SIZE]; |
| 69 | + |
| 70 | + snprintf(buf, BUF_SIZE, "%ld\n", (long)getpid()); |
| 71 | + if (write(pid_fd, buf, strlen(buf)) != (ssize_t)strlen(buf)) { |
| 72 | + fprintf(stderr, "Failed to write PID file '%s': %s\n", pid_file, strerror(errno)); |
| 73 | + goto finish; |
| 74 | + } |
| 75 | + |
| 76 | + ret = 0; |
| 77 | + |
| 78 | +finish: |
| 79 | + ocre_pid_file_release(); |
| 80 | + return 0; |
| 81 | +} |
0 commit comments