1/* 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 <errno.h> 27#include <string.h> 28#include <stdio.h> 29 30#include "debug.h" 31 32int pidfile_acquire(char *pidfile) 33{ 34 int pid_fd; 35 if (pidfile == NULL) return -1; 36 37 pid_fd = open(pidfile, O_CREAT | O_WRONLY, 0644); 38 if (pid_fd < 0) { 39 LOG(LOG_ERR, "Unable to open pidfile %s: %s\n", 40 pidfile, strerror(errno)); 41 } else { 42 lockf(pid_fd, F_LOCK, 0); 43 } 44 45 return pid_fd; 46} 47 48 49void pidfile_write_release(int pid_fd) 50{ 51 FILE *out; 52 53 if (pid_fd < 0) return; 54 55 if ((out = fdopen(pid_fd, "w")) != NULL) { 56 fprintf(out, "%d\n", getpid()); 57 fclose(out); 58 } 59 lockf(pid_fd, F_UNLCK, 0); 60 close(pid_fd); 61} 62 63 64void pidfile_delete(char *pidfile) 65{ 66 if (pidfile) unlink(pidfile); 67} 68 69 70