1 2#ifdef HAVE_CONFIG_H 3# include <config.h> 4#endif 5 6#include <unistd.h> 7#include <string.h> 8#include <stdio.h> 9#include <stdlib.h> 10#if HAVE_ERRNO_H 11# include <errno.h> 12#endif 13#if HAVE_SIGNAL_H 14# include <signal.h> 15#endif 16 17#include <error.h> 18#include <dprintf.h> 19 20int pid_file_create(char *pid_file) 21{ 22#if HAVE_GETPID 23 char buf[64]; 24 FILE* fp = NULL; 25 pid_t mypid; 26 pid_t otherpid = -1; 27 28#if HAVE_SETEUID && HAVE_SETEGID 29 gid_t oldegid = -1; 30 uid_t oldeuid = -1; 31#endif 32 33#if HAVE_SETEUID && HAVE_SETEGID 34 oldegid = getegid(); 35 oldeuid = geteuid(); 36 37 setegid(getgid()); 38 seteuid(getuid()); 39#endif 40 41 // check if the pid file exists 42 if((fp=fopen(pid_file, "r")) != NULL) 43 { 44 // if the pid file exists what does it say? 45 if(fgets(buf, sizeof(buf), fp) == NULL) 46 { 47 show_message("error reading pid file: %s (%s)\n", pid_file, error_string); 48 goto ERR; 49 } 50 fclose(fp); 51 otherpid = atoi(buf); 52 53 // check to see if the pid is valid 54 if(kill(otherpid, 0) == 0) 55 { 56 // if it is alive then we quit 57 show_message("there is another program already running with pid %d.\n", (int)otherpid); 58 goto ERR; 59 } 60 } 61 62 // create the pid file 63 if((fp=fopen(pid_file, "w")) == NULL) 64 { 65 show_message("could not create pid file: %s (%s)\n", pid_file, error_string); 66 goto ERR; 67 } 68 69 mypid = getpid(); 70 fprintf(fp, "%d\n", (int)mypid); 71 fclose(fp); 72 73 dprintf((stderr, "pid file %s successfully created with value %d.\n", 74 pid_file, (int)mypid)); 75 76#if HAVE_SETEUID && HAVE_SETEGID 77 setegid(oldegid); 78 seteuid(oldeuid); 79#endif 80 81 return 0; 82 83ERR: 84 if(fp) { fclose(fp); fp = NULL; } 85#if HAVE_SETEUID && HAVE_SETEGID 86 setegid(oldegid); 87 seteuid(oldeuid); 88#endif 89 return(-1); 90 91#else 92 return(-1); 93#endif 94} 95 96int pid_file_delete(char *pid_file) 97{ 98 int ret; 99 100#if HAVE_SETEUID && HAVE_SETEGID 101 gid_t oldegid = -1; 102 uid_t oldeuid = -1; 103#endif 104 105#if HAVE_SETEUID && HAVE_SETEGID 106 oldegid = getegid(); 107 oldeuid = geteuid(); 108 109 setegid(getgid()); 110 seteuid(getuid()); 111#endif 112 113 ret = unlink(pid_file); 114 115#if HAVE_SETEUID && HAVE_SETEGID 116 setegid(oldegid); 117 seteuid(oldeuid); 118#endif 119 120 return ret; 121} 122 123