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() */
15 int pidfile_create(const char *pidFile, pid_t pid)
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));
27 lock.l_type = F_WRLCK;
29 lock.l_whence = SEEK_SET;
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));
37 condlog(0, "process is already running");
40 if (ftruncate(fd, 0) < 0) {
41 condlog(0, "Cannot truncate pidfile [%s], error was [%s]",
42 pidFile, strerror(errno));
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));
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));
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));