sm

sysmgr implemented in C
git clone git://git.ckyln.com/sm
Log | Files | Refs | README | LICENSE

proc.c (1232B)


      1 #include <unistd.h>
      2 #include <stdio.h>
      3 #include <signal.h>
      4 #include <errno.h>
      5 
      6 #include "../util.h"
      7 
      8 pid_t
      9 getsvpid(service *sv)
     10 {
     11 	pid_t pid;
     12 
     13 	if (access(sv->pidfile, R_OK) == -1)
     14 		return -1;
     15 	FILE *pidfile;
     16 
     17 	pidfile = fopen(sv->pidfile, "r");
     18 	if (pidfile == NULL)
     19 		return -1;
     20 
     21 	fscanf(pidfile, "%d", &pid);
     22 	fclose(pidfile);
     23 
     24 	return pid;
     25 }
     26 
     27 pid_t
     28 getsyspid(service *sv)
     29 {
     30 	pid_t pid;
     31 
     32 	if (access(sv->syspidfile, R_OK) == -1) {
     33 		return -1;
     34 	}
     35 	FILE *pidfile;
     36 
     37 	pidfile = fopen(sv->syspidfile, "r");
     38 	if (pidfile == NULL)
     39 		return -1;
     40 
     41 	fscanf(pidfile, "%d", &pid);
     42 	fclose(pidfile);
     43 
     44 	return pid;
     45 }
     46 
     47 int
     48 writesvpid(char *file, pid_t pid)
     49 {
     50 	FILE *pidfile;
     51 
     52 	pidfile = fopen(file, "w");
     53 	if (pidfile == NULL) {
     54 		perror(file);
     55 		return -1;
     56 	}
     57 	fprintf(pidfile, "%d\n", pid);
     58 	fclose(pidfile);
     59 
     60 	return 0;
     61 }
     62 
     63 int
     64 checkprocess(int pid)
     65 {
     66 	if (kill(pid, 0) == 0) return 0;
     67 	else {
     68 		switch (errno) {
     69 		case 1:
     70 			/* EPERM is only produced if the process exists, but the
     71 			 * user running the program doesn't have the permissions
     72 			 * to kill the process. We can safely assume that the
     73 			 * process exists in this case and return 0.
     74 			 */
     75 			return 0;
     76 			break;
     77 		default:
     78 			perror("kill");
     79 			break;
     80 		}
     81 
     82 		return 1;
     83 	}
     84 }