slb

Sleep on Low Battery
Log | Files | Refs | README | LICENSE

slb.c (1554B)


      1 #include <err.h>
      2 #include <fcntl.h>
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 #include <syslog.h>
      6 #include <sys/types.h>
      7 #include <sys/stat.h>
      8 #include <sys/wait.h>
      9 #include <unistd.h>
     10 
     11 #include "config.h"
     12 
     13 void
     14 daemoninit(void)
     15 {
     16 	pid_t p;
     17 
     18 	if ((p = fork()) == -1) {
     19 		syslog(LOG_DAEMON|LOG_ERR, "fork error for %s: %m", "slb.c");
     20 		exit(1);
     21 	}
     22 	else if (p != 0)
     23 		exit(0);
     24 
     25 	setsid();
     26 	chdir("/root");
     27 	umask(0);
     28 }
     29 
     30 int
     31 pwread(const char *bat)
     32 {
     33 	char buf[4];
     34 	int fd;
     35 	int t;
     36 	
     37 	if ((fd = open(bat, O_RDONLY)) == -1) {
     38 		syslog(LOG_DAEMON|LOG_ERR, "open error for %s: %m", "slb.c");
     39 		exit(1);
     40 	}
     41 
     42 	if ((t = read(fd,buf,sizeof(buf))) == -1) {
     43 		syslog(LOG_DAEMON|LOG_ERR, "read error for %s: %m", "slb.c");
     44 		exit(1);
     45 	}
     46 
     47 	buf[t]=0;
     48 
     49 	close(fd);
     50 	
     51 	return atoi(buf);
     52 }
     53 
     54 int
     55 main(int argc, char **argv)
     56 {
     57 	(void) argc;
     58 	(void) argv;
     59 
     60 	int tpow;
     61 	int t;
     62 	pid_t p;
     63 	int slept = 0;		/* SET prior sleep */
     64 
     65 	openlog("slb", LOG_PID|LOG_CONS, LOG_DAEMON);
     66 	daemoninit();
     67 	for (;;) {
     68 		tpow = 0;
     69 
     70 		for (int i = 0; i < sizeof(bat)/sizeof(*bat); i++) {
     71 			tpow += pwread(bat[i]);
     72 		}
     73 
     74 		if (pwread(ac))
     75 			slept = 0;
     76 
     77 		if (!slept && !pwread(ac) && (tpow < threshold)) {
     78 			slept = 1;
     79 			if ((p = fork()) == -1) {
     80 				syslog(LOG_DAEMON|LOG_ERR,
     81 				       "fork error for %s: %m", "slb.c");
     82 				exit(1);
     83 			}
     84 			else if (p > 0) {
     85 				wait(NULL);
     86 			}
     87 			else if (p == 0) {
     88 				if ((t = execve(cmd, arg, NULL)) == -1) {
     89 					syslog(LOG_DAEMON|LOG_ERR,
     90 					       "execve error for %s: %m", "slb.c");
     91 					exit(1);
     92 				}
     93 			}
     94 		}
     95 		sleep(delay);
     96 	}
     97 
     98 	return 0;
     99 }