linux.c (2575B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 #include <time.h> 6 #include <unistd.h> 7 #include <X11/Xlib.h> 8 #include <sys/statfs.h> 9 10 #include "sbar.h" 11 12 void Batchk(); 13 void Partchk(); 14 void Partinit(); 15 void Ramchk(); 16 void Raminit(); 17 void Titleinit(); 18 void Titleset(); 19 void wait(double); 20 21 static Display* display; 22 23 void 24 Batchk() 25 { 26 FILE* f; 27 uint c; 28 29 if (!(f = fopen("/sys/class/power_supply/BAT0/capacity", "r"))) return; 30 fscanf(f, "%u", &c); 31 fclose(f); 32 if (c == bat.c) return; 33 bat.c = c; 34 sprintf(bat.text, "B(%u%%)", c % 100); 35 } 36 37 void 38 Partchk() 39 { 40 struct statfs stat; 41 uint i, free; 42 43 for (i = 0; part[i].path; ++i) { 44 statfs(part[i].path, &stat); 45 free = (stat.f_bavail * stat.f_bsize) >> 23; 46 if (free != part[i].free) { 47 part[i].free = free; 48 ++title.update; 49 snprintf(part[i].text, 32, "%s:(%2.2fGB/%2.2fGB)", part[i].path, part[i].size_f - ((float)free / 128.0f), part[i].size_f); 50 } 51 } 52 } 53 54 void 55 Partinit() 56 { 57 struct statfs stat; 58 uint i, size; 59 60 for (i = 0; part[i].path; ++i) { 61 statfs(part[i].path, &stat); 62 size = (stat.f_blocks * stat.f_bsize) >> 20; 63 part[i].size_f = (float)size / 1024.0f; 64 } 65 } 66 67 void 68 Ramchk() 69 { 70 FILE* meminfo; 71 char buf[1024]; 72 ulong i, free; 73 float used_f; 74 uchar unit; 75 76 if (!(meminfo = fopen("/proc/meminfo", "r"))) return; 77 fread(buf, 1024, 1, meminfo); 78 fclose(meminfo); 79 free = 0; 80 sscanf(strstr(buf, "MemFree"), "MemFree: %lu", &free); 81 if ((ram.unit == 'M' && free >> 3 == ram.free >> 3) || 82 (ram.unit == 'G' && free >> 13 == ram.free >> 13)) return; 83 ram.free = free; 84 sscanf(strstr(buf, "Buffers"), "Buffers: %lu", &i); 85 free += i; 86 sscanf(strstr(buf, "Cached"), "Cached: %lu", &i); 87 free += i; 88 sscanf(strstr(buf, "Shmem"), "Shmem: %lu", &i); 89 free -= i; 90 sscanf(strstr(buf, "SReclaimable"), "SReclaimable: %lu", &i); 91 free += i; 92 unit = 'M'; 93 used_f = (ram.size - free) / 1024.0f; 94 if (used_f > 1024) { 95 unit = 'G'; 96 used_f /= 1024.0f; 97 } 98 ++title.update; 99 snprintf(ram.text, 24, "R(%.02f%cB/%.02f%cB)", used_f, unit, ram.size_f, ram.unit); 100 } 101 102 void 103 Raminit() 104 { 105 FILE* meminfo; 106 char buf[32]; 107 ulong size; 108 109 if (!(meminfo = fopen("/proc/meminfo", "r"))) return; 110 fread(buf, 32, 1, meminfo); 111 fclose(meminfo); 112 sscanf(buf, "MemTotal: %lu", &size); 113 ram.size = size; 114 ram.unit = 'M'; 115 if (size > 1024*1024) { 116 ram.unit = 'G'; 117 size >>= 10; 118 } 119 ram.size_f = size/1024.0f; 120 } 121 122 void 123 Titleinit() 124 { 125 display = XOpenDisplay(NULL); 126 } 127 128 void 129 Titleset() 130 { 131 XStoreName(display, DefaultRootWindow(display), title.text); 132 XFlush(display); 133 } 134 135 void 136 wait(double t) 137 { 138 usleep((int)(t * 1000000)); 139 }