]> git.proxmox.com Git - mirror_frr.git/blob - lib/pid_output.c
Merge pull request #1237 from donaldsharp/distance_special
[mirror_frr.git] / lib / pid_output.c
1 /*
2 * Process id output.
3 * Copyright (C) 1998, 1999 Kunihiro Ishiguro
4 *
5 * This file is part of GNU Zebra.
6 *
7 * GNU Zebra is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2, or (at your option) any
10 * later version.
11 *
12 * GNU Zebra is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; see the file COPYING; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <zebra.h>
23 #include <fcntl.h>
24 #include <log.h>
25 #include "version.h"
26 #include "network.h"
27
28 #define PIDFILE_MASK 0644
29
30 pid_t pid_output(const char *path)
31 {
32 int tmp;
33 int fd;
34 pid_t pid;
35 char buf[16];
36 struct flock lock;
37 mode_t oldumask;
38
39 pid = getpid();
40
41 oldumask = umask(0777 & ~PIDFILE_MASK);
42 fd = open(path, O_RDWR | O_CREAT, PIDFILE_MASK);
43 if (fd < 0) {
44 zlog_err("Can't create pid lock file %s (%s), exiting", path,
45 safe_strerror(errno));
46 umask(oldumask);
47 exit(1);
48 } else {
49 size_t pidsize;
50
51 umask(oldumask);
52 memset(&lock, 0, sizeof(lock));
53
54 set_cloexec(fd);
55
56 lock.l_type = F_WRLCK;
57 lock.l_whence = SEEK_SET;
58
59 if (fcntl(fd, F_SETLK, &lock) < 0) {
60 zlog_err("Could not lock pid_file %s (%s), exiting",
61 path, safe_strerror(errno));
62 exit(1);
63 }
64
65 sprintf(buf, "%d\n", (int)pid);
66 pidsize = strlen(buf);
67 if ((tmp = write(fd, buf, pidsize)) != (int)pidsize)
68 zlog_err(
69 "Could not write pid %d to pid_file %s, rc was %d: %s",
70 (int)pid, path, tmp, safe_strerror(errno));
71 else if (ftruncate(fd, pidsize) < 0)
72 zlog_err(
73 "Could not truncate pid_file %s to %u bytes: %s",
74 path, (u_int)pidsize, safe_strerror(errno));
75 }
76 return pid;
77 }