util.c (1443B)
1 /* See LICENSE for copyright information 2 * 3 * These are shared functions for utility programs. This may be used for a 4 * library in the future. 5 */ 6 #include <stdio.h> 7 #include <stdlib.h> 8 #include <string.h> 9 #include <signal.h> 10 #include <stdarg.h> 11 #include <errno.h> 12 13 #include "util.h" 14 15 extern int errno; 16 17 char* 18 getenv_fallback(char *name, char *fallback) 19 { 20 char *value = getenv(name); 21 if ( ! value ) value = fallback; 22 return value; 23 } 24 25 service* 26 sv_init(service *sv, char *sv_name) 27 { 28 sprintf(sv->name, "%s", sv_name); 29 sprintf(sv->sysdir, "%s", getenv_fallback("SYSDIR", "/var/sysmgr")); 30 sprintf(sv->rundir, "%s", getenv_fallback("RUNDIR", "/run/sysmgr")); 31 sprintf(sv->pidfile, "%s/%s/pid", sv->rundir, sv->name); 32 sprintf(sv->svfile, "%s/%s", sv->sysdir, sv_name); 33 34 return sv; 35 } 36 37 void 38 die(const char *msg, ...) 39 { 40 va_list ap; 41 42 va_start(ap, msg); 43 vfprintf(stderr, msg, ap); 44 va_end(ap); 45 46 if (msg[0] && msg[strlen(msg)-1] == ':') { 47 fputc(' ', stderr); 48 perror(NULL); 49 } else { 50 fputc('\n', stderr); 51 } 52 exit(1); 53 } 54 55 int 56 checkprocess(int pid) 57 { 58 if (kill(pid, 0) == 0) return 0; 59 else { 60 switch (errno) { 61 case 1: 62 /* EPERM is only produced if the process exists, but the 63 * user running the program doesn't have the permissions 64 * to kill the process. We can safely assume that the 65 * process exists in this case and return 0. 66 */ 67 return 0; 68 break; 69 default: 70 perror("kill"); 71 break; 72 } 73 74 return 1; 75 } 76 }