blob: e00e47ac611ec6ac9536f153a1e92c67c45b0337 [file] [log] [blame]
paul718e3742002-12-13 20:15:29 +00001/*
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>
paule92fbaf2003-10-24 04:10:16 +000024#include <fcntl.h>
25#include <log.h>
26
27pid_t pid_output_lock(char *);
paul718e3742002-12-13 20:15:29 +000028
29pid_t
30pid_output (char *path)
31{
paule92fbaf2003-10-24 04:10:16 +000032#ifndef HAVE_FCNTL
paul718e3742002-12-13 20:15:29 +000033 FILE *fp;
34 pid_t pid;
35
36 pid = getpid();
37
38 fp = fopen (path, "w");
39 if (fp != NULL)
40 {
41 fprintf (fp, "%d\n", (int) pid);
42 fclose (fp);
43 return -1;
44 }
45 return pid;
paule92fbaf2003-10-24 04:10:16 +000046#else
47 return pid_output_lock(path);
48#endif /* HAVE_FCNTL */
paul718e3742002-12-13 20:15:29 +000049}
50
paule92fbaf2003-10-24 04:10:16 +000051#ifdef HAVE_FCNTL
paul718e3742002-12-13 20:15:29 +000052pid_t
53pid_output_lock (char *path)
54{
55 int tmp;
56 int fd;
57 pid_t pid;
paule92fbaf2003-10-24 04:10:16 +000058 char buf[16];
59 struct flock lock = { .l_type = F_WRLCK,
60 .l_whence = SEEK_END };
paul718e3742002-12-13 20:15:29 +000061
62 pid = getpid ();
63
paule92fbaf2003-10-24 04:10:16 +000064 fd = open (path, O_RDWR | O_CREAT, 0644);
paul718e3742002-12-13 20:15:29 +000065 if (fd < 0)
paul718e3742002-12-13 20:15:29 +000066 {
paule92fbaf2003-10-24 04:10:16 +000067 zlog_err( "Can't creat pid lock file %s (%s), exit",
68 path, strerror(errno));
paul718e3742002-12-13 20:15:29 +000069 exit (-1);
70 }
71 else
72 {
paule92fbaf2003-10-24 04:10:16 +000073 memset (&lock, 0, sizeof(lock));
74
75 if (fcntl(fd, F_SETLK, &lock) < 0)
76 {
77 zlog_err("Could not lock pid_file %s, exit", path);
78 exit (-1);
79 }
80
paul718e3742002-12-13 20:15:29 +000081 sprintf (buf, "%d\n", (int) pid);
82 tmp = write (fd, buf, strlen (buf));
paul718e3742002-12-13 20:15:29 +000083 }
paul718e3742002-12-13 20:15:29 +000084 return pid;
85}
paule92fbaf2003-10-24 04:10:16 +000086#endif /* HAVE_FCNTL */