blob: d656c7ad0ee2e85a8588d15b404a914450f3db72 [file] [log] [blame]
Russ Dill4e864a32003-12-18 22:25:38 +00001/* pidfile.c
2 *
3 * Functions to assist in the writing and removing of pidfiles.
4 *
5 * Russ Dill <Russ.Dill@asu.edu> Soptember 2001
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22#include <sys/types.h>
23#include <sys/stat.h>
24#include <fcntl.h>
25#include <unistd.h>
26#include <stdio.h>
27#include <stdlib.h>
28
29#include "pidfile.h"
30#include "common.h"
31
32static char *saved_pidfile;
33
34static void pidfile_delete(void)
35{
36 if (saved_pidfile) unlink(saved_pidfile);
37}
38
39
40int pidfile_acquire(const char *pidfile)
41{
42 int pid_fd;
43 if (!pidfile) return -1;
44
45 pid_fd = open(pidfile, O_CREAT | O_WRONLY, 0644);
46 if (pid_fd < 0) {
47 LOG(LOG_ERR, "Unable to open pidfile %s: %m\n", pidfile);
48 } else {
49 lockf(pid_fd, F_LOCK, 0);
50 if (!saved_pidfile)
51 atexit(pidfile_delete);
52 saved_pidfile = (char *) pidfile;
53 }
54
55 return pid_fd;
56}
57
58
59void pidfile_write_release(int pid_fd)
60{
61 FILE *out;
62
63 if (pid_fd < 0) return;
64
65 if ((out = fdopen(pid_fd, "w")) != NULL) {
66 fprintf(out, "%d\n", getpid());
67 fclose(out);
68 }
69 lockf(pid_fd, F_UNLCK, 0);
70 close(pid_fd);
71}
72
73
74
75