[build] legacy files update
[platform/upstream/multipath-tools.git] / multipathd / pidfile.c
1 #include <sys/types.h> /* for pid_t */
2 #include <sys/stat.h>  /* for open */
3 #include <signal.h>    /* for kill() */
4 #include <errno.h>     /* for ESHRC */
5 #include <stdio.h>     /* for f...() */
6 #include <string.h>    /* for memset() */
7 #include <stdlib.h>    /* for atoi() */
8 #include <unistd.h>    /* for unlink() */
9 #include <fcntl.h>     /* for fcntl() */
10
11 #include <debug.h>
12
13 #include "pidfile.h"
14
15 int pidfile_create(const char *pidFile, pid_t pid)
16 {
17         char buf[20];
18         struct flock lock;
19         int fd, value;
20
21         if((fd = open(pidFile, O_WRONLY | O_CREAT,
22                        (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) < 0) {
23                 condlog(0, "Cannot open pidfile [%s], error was [%s]",
24                         pidFile, strerror(errno));
25                 return 1;
26         }
27         lock.l_type = F_WRLCK;
28         lock.l_start = 0;
29         lock.l_whence = SEEK_SET;
30         lock.l_len = 0;
31
32         if (fcntl(fd, F_SETLK, &lock) < 0) {
33                 if (errno != EACCES && errno != EAGAIN)
34                         condlog(0, "Cannot lock pidfile [%s], error was [%s]",
35                                 pidFile, strerror(errno));
36                 else
37                         condlog(0, "process is already running");
38                 goto fail;
39         }
40         if (ftruncate(fd, 0) < 0) {
41                 condlog(0, "Cannot truncate pidfile [%s], error was [%s]",
42                         pidFile, strerror(errno));
43                 goto fail;
44         }
45         memset(buf, 0, sizeof(buf));
46         snprintf(buf, sizeof(buf)-1, "%u", pid);
47         if (write(fd, buf, strlen(buf)) != strlen(buf)) {
48                 condlog(0, "Cannot write pid to pidfile [%s], error was [%s]",
49                         pidFile, strerror(errno));
50                 goto fail;
51         }
52         if ((value = fcntl(fd, F_GETFD, 0)) < 0) {
53                 condlog(0, "Cannot get close-on-exec flag from pidfile [%s], "
54                         "error was [%s]", pidFile, strerror(errno));
55                 goto fail;
56         }
57         value |= FD_CLOEXEC;
58         if (fcntl(fd, F_SETFD, value) < 0) {
59                 condlog(0, "Cannot set close-on-exec flag from pidfile [%s], "
60                         "error was [%s]", pidFile, strerror(errno));
61                 goto fail;
62         }
63         return 0;
64 fail:
65         close(fd);
66         return 1;
67 }