blob: 125ca4031cc25d917cc54d5483a34208472aa31b [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];
paule4eaf1d2003-10-30 21:58:06 +000059 struct flock lock;
paul718e3742002-12-13 20:15:29 +000060
61 pid = getpid ();
62
paule92fbaf2003-10-24 04:10:16 +000063 fd = open (path, O_RDWR | O_CREAT, 0644);
paul718e3742002-12-13 20:15:29 +000064 if (fd < 0)
paul718e3742002-12-13 20:15:29 +000065 {
paule92fbaf2003-10-24 04:10:16 +000066 zlog_err( "Can't creat pid lock file %s (%s), exit",
67 path, strerror(errno));
paul718e3742002-12-13 20:15:29 +000068 exit (-1);
69 }
70 else
71 {
paule92fbaf2003-10-24 04:10:16 +000072 memset (&lock, 0, sizeof(lock));
73
paule4eaf1d2003-10-30 21:58:06 +000074 lock.l_type = F_WRLCK;
75 lock.l_whence = SEEK_END;
76
paule92fbaf2003-10-24 04:10:16 +000077 if (fcntl(fd, F_SETLK, &lock) < 0)
78 {
79 zlog_err("Could not lock pid_file %s, exit", path);
80 exit (-1);
81 }
82
paul718e3742002-12-13 20:15:29 +000083 sprintf (buf, "%d\n", (int) pid);
84 tmp = write (fd, buf, strlen (buf));
paul718e3742002-12-13 20:15:29 +000085 }
paul718e3742002-12-13 20:15:29 +000086 return pid;
87}
paule92fbaf2003-10-24 04:10:16 +000088#endif /* HAVE_FCNTL */