]> git.proxmox.com Git - mirror_frr.git/blob - lib/pid_output.c
de4c2fba991e873e1d269b6b1a07e3cd152f374c
[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
18 * along with GNU Zebra; see the file COPYING. If not, write to the Free
19 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 * 02111-1307, USA.
21 */
22
23 #include <zebra.h>
24 #include <fcntl.h>
25 #include <log.h>
26 #include "version.h"
27 #include "network.h"
28
29 #define PIDFILE_MASK 0644
30 #ifndef HAVE_FCNTL
31
32 pid_t
33 pid_output (const char *path)
34 {
35 FILE *fp;
36 pid_t pid;
37 mode_t oldumask;
38
39 pid = getpid();
40
41 oldumask = umask(0777 & ~PIDFILE_MASK);
42 fp = fopen (path, "w");
43 if (fp != NULL)
44 {
45 fprintf (fp, "%d\n", (int) pid);
46 fclose (fp);
47 umask(oldumask);
48 return pid;
49 }
50 /* XXX Why do we continue instead of exiting? This seems incompatible
51 with the behavior of the fcntl version below. */
52 zlog_warn("Can't fopen pid lock file %s (%s), continuing",
53 path, safe_strerror(errno));
54 umask(oldumask);
55 return -1;
56 }
57
58 #else /* HAVE_FCNTL */
59
60 pid_t
61 pid_output (const char *path)
62 {
63 int tmp;
64 int fd;
65 pid_t pid;
66 char buf[16];
67 struct flock lock;
68 mode_t oldumask;
69
70 pid = getpid ();
71
72 oldumask = umask(0777 & ~PIDFILE_MASK);
73 fd = open (path, O_RDWR | O_CREAT, PIDFILE_MASK);
74 if (fd < 0)
75 {
76 zlog_err("Can't create pid lock file %s (%s), exiting",
77 path, safe_strerror(errno));
78 umask(oldumask);
79 exit(1);
80 }
81 else
82 {
83 size_t pidsize;
84
85 umask(oldumask);
86 memset (&lock, 0, sizeof(lock));
87
88 set_cloexec(fd);
89
90 lock.l_type = F_WRLCK;
91 lock.l_whence = SEEK_SET;
92
93 if (fcntl(fd, F_SETLK, &lock) < 0)
94 {
95 zlog_err("Could not lock pid_file %s, exiting", path);
96 exit(1);
97 }
98
99 sprintf (buf, "%d\n", (int) pid);
100 pidsize = strlen(buf);
101 if ((tmp = write (fd, buf, pidsize)) != (int)pidsize)
102 zlog_err("Could not write pid %d to pid_file %s, rc was %d: %s",
103 (int)pid,path,tmp,safe_strerror(errno));
104 else if (ftruncate(fd, pidsize) < 0)
105 zlog_err("Could not truncate pid_file %s to %u bytes: %s",
106 path,(u_int)pidsize,safe_strerror(errno));
107 }
108 return pid;
109 }
110
111 #endif /* HAVE_FCNTL */