diff --git a/.gitignore b/.gitignore index 2182f77..440553c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ *.swp *.o bmon* +!bmon.c diff --git a/bmon.c b/bmon.c index bdf9369..fb6f20e 100644 --- a/bmon.c +++ b/bmon.c @@ -1,10 +1,83 @@ #include #include +#include +#include +#include +#include +#include +#include +#include +#include -char *bat_power_path = "/sys/class/power_supply/BAT1/energy_now"; -char *bat_capacity_path = "/sys/class/power_supply/BAT1/capacity"; +//char *bat_power_path = "/sys/class/power_supply/BAT1/energy_now"; +//char *bat_capacity_path = "/sys/class/power_supply/BAT1/capacity"; + +const char *bat_base_path = "/sys/class/power_supply/"; + +void usage (void) +{ + printf("usage: bmon [-w]\n"); +} int main (int argc, char *argv[]) { + int wflag = 0; + int opc; + while ((opc = getopt(argc, argv, "w")) != -1) { + switch (opc) { + case 'w': + wflag = 1; + break; + default: /* '?' */ + usage(); + exit(1); + break; + } + + } + + DIR *bdir = NULL; + if (!(bdir = opendir(bat_base_path))) + perror("error opening base directory"); + + struct dirent *ent = NULL; + int *fd_list = NULL; + int fd_num = 0; + for (;;) { + errno = 0; + if (!(ent = readdir(bdir))) { + if (errno) + perror("error reading base directory"); + else break; + } + + if (!strstr(ent->d_name, "BAT1")) + continue; + + int fd; + char path[sizeof(bat_base_path) + 256 + 64]; + strcpy(path, bat_base_path); + strcat(path, ent->d_name); + if (wflag) + strcat(path, "/energy_now"); + else strcat(path, "/capacity"); + + if ((fd = open(path, O_RDONLY | O_NONBLOCK)) != -1) { + int *tmp = NULL; + tmp = realloc(fd_list, sizeof(int) * (fd_num + 1)); + if (!tmp) + perror("failed realloc"); + fd_list = tmp; + fd_list[fd_num] = fd; + fd_num++; + } else printf("err: %s\n", strerror(errno)); + + } + closedir(bdir); + if (!fd_num) + printf("no files were opened\n"); + + for (int i = 0; i < fd_num; i++) + close(fd_list[i]); return 0; } diff --git a/makefile b/makefile new file mode 100644 index 0000000..1ae9683 --- /dev/null +++ b/makefile @@ -0,0 +1,12 @@ +CC = gcc +CFLAGS = -Wall -Werror -pedantic -O2 + +bmon: bmon.o + +debug: + gcc $(CFLAGS) -g bmon.c -o bmon-dbg + +bmon.o: bmon.c + +clean: + rm *.o bmon bmon-dbg 2> /dev/null