]> git.proxmox.com Git - mirror_frr.git/blob - lib/pid_output.c
Merge pull request #12798 from donaldsharp/rib_match_multicast
[mirror_frr.git] / lib / pid_output.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Process id output.
4 * Copyright (C) 1998, 1999 Kunihiro Ishiguro
5 */
6
7 #include <zebra.h>
8 #include <fcntl.h>
9 #include <log.h>
10 #include "lib/version.h"
11 #include "network.h"
12 #include "lib_errors.h"
13
14 #define PIDFILE_MASK 0644
15
16 pid_t pid_output(const char *path)
17 {
18 int tmp;
19 int fd;
20 pid_t pid;
21 char buf[16];
22 struct flock lock;
23 mode_t oldumask;
24
25 pid = getpid();
26
27 oldumask = umask(0777 & ~PIDFILE_MASK);
28 fd = open(path, O_RDWR | O_CREAT, PIDFILE_MASK);
29 if (fd < 0) {
30 flog_err_sys(EC_LIB_SYSTEM_CALL,
31 "Can't create pid lock file %s (%s), exiting",
32 path, safe_strerror(errno));
33 umask(oldumask);
34 exit(1);
35 } else {
36 size_t pidsize;
37
38 umask(oldumask);
39 memset(&lock, 0, sizeof(lock));
40
41 set_cloexec(fd);
42
43 lock.l_type = F_WRLCK;
44 lock.l_whence = SEEK_SET;
45
46 if (fcntl(fd, F_SETLK, &lock) < 0) {
47 flog_err_sys(EC_LIB_SYSTEM_CALL,
48 "Could not lock pid_file %s (%s), exiting. Please ensure that the daemon is not already running",
49 path, safe_strerror(errno));
50 exit(1);
51 }
52
53 snprintf(buf, sizeof(buf), "%d\n", (int)pid);
54 pidsize = strlen(buf);
55 if ((tmp = write(fd, buf, pidsize)) != (int)pidsize)
56 flog_err_sys(
57 EC_LIB_SYSTEM_CALL,
58 "Could not write pid %d to pid_file %s, rc was %d: %s",
59 (int)pid, path, tmp, safe_strerror(errno));
60 else if (ftruncate(fd, pidsize) < 0)
61 flog_err_sys(
62 EC_LIB_SYSTEM_CALL,
63 "Could not truncate pid_file %s to %u bytes: %s",
64 path, (unsigned int)pidsize,
65 safe_strerror(errno));
66 }
67 return pid;
68 }