-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem_monitor.cpp
More file actions
975 lines (801 loc) · 35.9 KB
/
system_monitor.cpp
File metadata and controls
975 lines (801 loc) · 35.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <cstring>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/statvfs.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <curl/curl.h>
#include <thread>
#include <chrono>
#include <iomanip>
#include <algorithm>
#include <tuple>
#include <csignal>
#include <termios.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <map>
#include <set>
class SystemMonitor {
private:
volatile bool running;
struct termios orig_termios;
int terminal_width;
int terminal_height;
struct CoreData {
long user, nice, system, idle, iowait, irq, softirq;
long total() const { return user + nice + system + idle + iowait + irq + softirq; }
};
struct NetworkInterface {
std::string name;
std::string ip;
std::string mac;
unsigned long long rx_bytes;
unsigned long long tx_bytes;
unsigned long long rx_speed;
unsigned long long tx_speed;
bool is_wifi;
};
struct DiskStats {
unsigned long long reads_completed;
unsigned long long reads_merged;
unsigned long long sectors_read;
unsigned long long time_reading;
unsigned long long writes_completed;
unsigned long long writes_merged;
unsigned long long sectors_written;
unsigned long long time_writing;
unsigned long long io_in_progress;
unsigned long long time_io;
unsigned long long weighted_time_io;
};
struct DiskInfo {
std::string device;
std::string mount_point;
std::string fstype;
unsigned long long total;
unsigned long long used;
unsigned long long free;
double usage_percent;
DiskStats stats;
unsigned long long read_speed;
unsigned long long write_speed;
};
std::vector<CoreData> prevCores;
std::vector<double> coreUsage;
std::vector<std::tuple<double, std::string, std::string>> processList;
std::map<std::string, NetworkInterface> networkInterfaces;
std::map<std::string, DiskStats> prevDiskStats;
std::vector<DiskInfo> diskInfo;
double memTotal, memAvailable, memUsed, memPercent;
double swapTotal, swapUsed, swapPercent;
std::string publicIP;
std::string hostname;
std::string kernelVersion;
long uptime_seconds;
int total_processes;
int running_processes;
double load_avg_1min, load_avg_5min, load_avg_15min;
const std::string COLOR_RESET = "\033[0m";
const std::string COLOR_RED = "\033[31m";
const std::string COLOR_GREEN = "\033[32m";
const std::string COLOR_YELLOW = "\033[33m";
const std::string COLOR_BLUE = "\033[34m";
const std::string COLOR_MAGENTA = "\033[35m";
const std::string COLOR_CYAN = "\033[36m";
const std::string COLOR_WHITE = "\033[37m";
const std::string COLOR_BOLD = "\033[1m";
const std::string BOX_TL = "+";
const std::string BOX_TR = "+";
const std::string BOX_BL = "+";
const std::string BOX_BR = "+";
const std::string BOX_H = "-";
const std::string BOX_V = "|";
void clearScreen() {
std::cout << "\033[2J\033[1;1H";
}
void hideCursor() {
std::cout << "\033[?25l";
std::cout.flush();
}
void showCursor() {
std::cout << "\033[?25h";
std::cout.flush();
}
void moveCursor(int row, int col) {
std::cout << "\033[" << row << ";" << col << "H";
}
void getTerminalSize() {
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
terminal_width = w.ws_col;
terminal_height = w.ws_row;
if (terminal_width < 120) terminal_width = 120;
if (terminal_height < 35) terminal_height = 35;
}
void drawText(int row, int col, const std::string& text, const std::string& color = "") {
moveCursor(row, col);
if (!color.empty()) std::cout << color;
std::cout << text;
if (!color.empty()) std::cout << COLOR_RESET;
}
void drawProgressBar(int row, int col, int width, double percent, const std::string& color) {
moveCursor(row, col);
int fillWidth = static_cast<int>((percent / 100.0) * (width - 2));
std::cout << "[";
for (int i = 0; i < width - 2; i++) {
if (i < fillWidth) {
std::cout << color << "#" << COLOR_RESET;
} else {
std::cout << ".";
}
}
std::cout << "]";
}
std::vector<CoreData> readCPUStats() {
std::vector<CoreData> cores;
std::ifstream file("/proc/stat");
std::string line;
while (std::getline(file, line)) {
if (line.substr(0, 3) == "cpu" && line.size() > 3 && isdigit(line[3])) {
std::istringstream iss(line);
std::string cpu;
CoreData data;
iss >> cpu >> data.user >> data.nice >> data.system >> data.idle
>> data.iowait >> data.irq >> data.softirq;
cores.push_back(data);
}
}
return cores;
}
void updateCPUUsage() {
auto currentCores = readCPUStats();
if (prevCores.empty()) {
prevCores = currentCores;
coreUsage.resize(currentCores.size(), 0.0);
return;
}
coreUsage.clear();
for (size_t i = 0; i < currentCores.size(); i++) {
long totalDiff = currentCores[i].total() - prevCores[i].total();
long idleDiff = (currentCores[i].idle + currentCores[i].iowait) -
(prevCores[i].idle + prevCores[i].iowait);
if (totalDiff > 0) {
double usage = (1.0 - static_cast<double>(idleDiff) / totalDiff) * 100.0;
coreUsage.push_back(usage);
} else {
coreUsage.push_back(0.0);
}
}
prevCores = currentCores;
}
void updateLoadAverage() {
std::ifstream file("/proc/loadavg");
file >> load_avg_1min >> load_avg_5min >> load_avg_15min;
}
void updateMemoryInfo() {
std::ifstream file("/proc/meminfo");
std::string line;
long total = 0, available = 0, swapTotal = 0, swapFree = 0;
while (std::getline(file, line)) {
if (line.substr(0, 9) == "MemTotal:") {
std::sscanf(line.c_str(), "MemTotal: %ld kB", &total);
} else if (line.substr(0, 13) == "MemAvailable:") {
std::sscanf(line.c_str(), "MemAvailable: %ld kB", &available);
} else if (line.substr(0, 10) == "SwapTotal:") {
std::sscanf(line.c_str(), "SwapTotal: %ld kB", &swapTotal);
} else if (line.substr(0, 9) == "SwapFree:") {
std::sscanf(line.c_str(), "SwapFree: %ld kB", &swapFree);
}
}
memTotal = total / 1024.0;
memAvailable = available / 1024.0;
memUsed = memTotal - memAvailable;
memPercent = (memUsed / memTotal) * 100.0;
this->swapTotal = swapTotal / 1024.0;
swapUsed = this->swapTotal - (swapFree / 1024.0);
swapPercent = this->swapTotal > 0 ? (swapUsed / this->swapTotal) * 100.0 : 0.0;
}
DiskStats readDiskStats(const std::string& device) {
DiskStats stats = {0};
std::ifstream file("/proc/diskstats");
std::string line;
while (std::getline(file, line)) {
std::istringstream iss(line);
int major, minor;
std::string dev_name;
iss >> major >> minor >> dev_name;
if (dev_name == device) {
iss >> stats.reads_completed >> stats.reads_merged >> stats.sectors_read
>> stats.time_reading >> stats.writes_completed >> stats.writes_merged
>> stats.sectors_written >> stats.time_writing >> stats.io_in_progress
>> stats.time_io >> stats.weighted_time_io;
break;
}
}
return stats;
}
void updateDiskInfo() {
diskInfo.clear();
std::ifstream mounts("/proc/mounts");
std::string line;
std::set<std::string> seen_devices;
while (std::getline(mounts, line)) {
std::istringstream iss(line);
std::string device, mount_point, fstype, options;
iss >> device >> mount_point >> fstype >> options;
if ((fstype == "ext4" || fstype == "ext3" || fstype == "ext2" ||
fstype == "btrfs" || fstype == "xfs" || fstype == "ntfs" ||
fstype == "vfat" || fstype == "fuseblk") && device.find("/dev/") == 0) {
if (mount_point.find("/snap/") == 0 ||
mount_point.find("/var/lib/docker") == 0 ||
mount_point == "/boot" || mount_point == "/boot/efi") continue;
struct statvfs stat;
if (statvfs(mount_point.c_str(), &stat) == 0) {
DiskInfo disk;
disk.device = device.substr(5);
disk.mount_point = mount_point;
disk.fstype = fstype;
unsigned long long block_size = stat.f_frsize;
unsigned long long total_blocks = stat.f_blocks;
unsigned long long free_blocks = stat.f_bfree;
disk.total = (total_blocks * block_size) / (1024 * 1024);
disk.free = (free_blocks * block_size) / (1024 * 1024);
disk.used = disk.total - disk.free;
disk.usage_percent = (static_cast<double>(disk.used) / disk.total) * 100.0;
DiskStats current_stats = readDiskStats(disk.device);
std::map<std::string, DiskStats>::iterator it = prevDiskStats.find(disk.device);
if (it != prevDiskStats.end()) {
unsigned long long sectors_read_diff = current_stats.sectors_read - it->second.sectors_read;
unsigned long long sectors_written_diff = current_stats.sectors_written - it->second.sectors_written;
disk.read_speed = (sectors_read_diff * 512) * 2 / 1024;
disk.write_speed = (sectors_written_diff * 512) * 2 / 1024;
} else {
disk.read_speed = 0;
disk.write_speed = 0;
}
disk.stats = current_stats;
prevDiskStats[disk.device] = current_stats;
diskInfo.push_back(disk);
seen_devices.insert(disk.device);
}
}
}
for (std::map<std::string, DiskStats>::iterator it = prevDiskStats.begin();
it != prevDiskStats.end(); ) {
if (seen_devices.find(it->first) == seen_devices.end()) {
prevDiskStats.erase(it++);
} else {
++it;
}
}
}
void updateNetworkInterfaces() {
std::map<std::string, std::pair<unsigned long long, unsigned long long>> prevStats;
for (std::map<std::string, NetworkInterface>::iterator it = networkInterfaces.begin();
it != networkInterfaces.end(); ++it) {
prevStats[it->first] = std::make_pair(it->second.rx_bytes, it->second.tx_bytes);
}
networkInterfaces.clear();
std::ifstream file("/proc/net/dev");
std::string line;
std::getline(file, line);
std::getline(file, line);
while (std::getline(file, line)) {
size_t colon = line.find(':');
if (colon != std::string::npos) {
std::string iface_name = line.substr(0, colon);
iface_name.erase(0, iface_name.find_first_not_of(" \t"));
iface_name.erase(iface_name.find_last_not_of(" \t") + 1);
if (iface_name == "lo") continue;
NetworkInterface netif;
netif.name = iface_name;
netif.is_wifi = (iface_name.find("wlan") != std::string::npos ||
iface_name.find("wlp") != std::string::npos ||
iface_name.find("wlx") != std::string::npos);
std::string data = line.substr(colon + 1);
std::istringstream iss(data);
iss >> netif.rx_bytes;
unsigned long long dummy;
iss >> dummy;
iss >> dummy;
iss >> dummy;
iss >> dummy;
iss >> dummy;
iss >> dummy;
iss >> dummy;
iss >> netif.tx_bytes;
std::map<std::string, std::pair<unsigned long long, unsigned long long>>::iterator it = prevStats.find(iface_name);
if (it != prevStats.end()) {
netif.rx_speed = (netif.rx_bytes - it->second.first) * 2 / 1024;
netif.tx_speed = (netif.tx_bytes - it->second.second) * 2 / 1024;
} else {
netif.rx_speed = 0;
netif.tx_speed = 0;
}
struct ifaddrs *ifaddr, *ifa;
if (getifaddrs(&ifaddr) == 0) {
for (ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
if (ifa->ifa_name != nullptr && strcmp(ifa->ifa_name, iface_name.c_str()) == 0 && ifa->ifa_addr != nullptr) {
if (ifa->ifa_addr->sa_family == AF_INET) {
char ip[INET_ADDRSTRLEN];
struct sockaddr_in* addr = (struct sockaddr_in*)ifa->ifa_addr;
inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof(ip));
netif.ip = ip;
break;
}
}
}
freeifaddrs(ifaddr);
}
std::string macPath = "/sys/class/net/" + iface_name + "/address";
std::ifstream macFile(macPath.c_str());
if (macFile.is_open()) {
std::getline(macFile, netif.mac);
}
if (netif.mac.empty()) netif.mac = "00:00:00:00:00:00";
if (netif.ip.empty()) netif.ip = "Not assigned";
networkInterfaces[iface_name] = netif;
}
}
}
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* output) {
size_t totalSize = size * nmemb;
output->append(static_cast<char*>(contents), totalSize);
return totalSize;
}
void updatePublicIP() {
CURL* curl = curl_easy_init();
std::string newIP;
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://api.ipify.org");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &newIP);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK && !newIP.empty()) {
newIP.erase(std::remove_if(newIP.begin(), newIP.end(),
[](unsigned char c) { return std::isspace(c); }), newIP.end());
if (!newIP.empty() && newIP.find_first_not_of("0123456789.") == std::string::npos) {
publicIP = newIP;
}
}
curl_easy_cleanup(curl);
}
if (publicIP.empty()) {
publicIP = "N/A (offline)";
}
}
void updateHostname() {
char host[256];
if (gethostname(host, sizeof(host)) == 0) {
hostname = host;
} else {
hostname = "unknown";
}
}
void updateKernelVersion() {
std::ifstream file("/proc/version");
std::getline(file, kernelVersion);
size_t start = kernelVersion.find("version ");
if (start != std::string::npos) {
start += 8;
size_t end = kernelVersion.find(' ', start);
if (end != std::string::npos) {
kernelVersion = kernelVersion.substr(start, end - start);
}
}
}
void updateUptime() {
std::ifstream file("/proc/uptime");
double uptime;
file >> uptime;
uptime_seconds = static_cast<long>(uptime);
}
void updateProcessInfo() {
total_processes = 0;
running_processes = 0;
processList.clear();
DIR* dir = opendir("/proc");
if (!dir) return;
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_type == DT_DIR) {
char* endptr;
long pid = strtol(entry->d_name, &endptr, 10);
if (*endptr == '\0') {
total_processes++;
std::string statPath = "/proc/" + std::string(entry->d_name) + "/stat";
std::ifstream statFile(statPath.c_str());
if (statFile.is_open()) {
std::string line;
std::getline(statFile, line);
size_t start = line.find('(');
size_t end = line.find(')');
if (start != std::string::npos && end != std::string::npos) {
std::string procName = line.substr(start + 1, end - start - 1);
std::string after = line.substr(end + 2);
std::istringstream iss(after);
std::vector<std::string> fields;
std::string field;
while (iss >> field) {
fields.push_back(field);
}
if (fields.size() >= 3) {
if (fields.size() > 2 && fields[2] == "R") {
running_processes++;
}
}
if (fields.size() >= 14) {
unsigned long utime = std::stoul(fields[11]);
unsigned long stime = std::stoul(fields[12]);
unsigned long totalTime = utime + stime;
double cpuEstimate = totalTime / 100.0;
processList.emplace_back(cpuEstimate, std::to_string(pid), procName);
}
}
}
}
}
}
closedir(dir);
std::sort(processList.begin(), processList.end(),
[](const std::tuple<double, std::string, std::string>& a,
const std::tuple<double, std::string, std::string>& b) {
return std::get<0>(a) > std::get<0>(b);
});
if (processList.size() > 10) {
processList.resize(10);
}
}
std::string formatUptime(long seconds) {
long days = seconds / 86400;
long hours = (seconds % 86400) / 3600;
long minutes = (seconds % 3600) / 60;
long secs = seconds % 60;
std::ostringstream oss;
if (days > 0) oss << days << "d ";
if (hours > 0 || days > 0) oss << hours << "h ";
if (minutes > 0 || hours > 0 || days > 0) oss << minutes << "m ";
oss << secs << "s";
return oss.str();
}
std::string formatSize(double size_kb) {
if (size_kb >= 1024 * 1024) {
return std::to_string(static_cast<int>(size_kb / (1024 * 1024))) + " GB";
} else if (size_kb >= 1024) {
return std::to_string(static_cast<int>(size_kb / 1024)) + " MB";
} else {
return std::to_string(static_cast<int>(size_kb)) + " KB";
}
}
std::string formatDiskSize(double size_mb) {
if (size_mb >= 1024 * 1024) {
return std::to_string(static_cast<int>(size_mb / (1024 * 1024))) + " TB";
} else if (size_mb >= 1024) {
return std::to_string(static_cast<int>(size_mb / 1024)) + " GB";
} else {
return std::to_string(static_cast<int>(size_mb)) + " MB";
}
}
std::string makeHorizontalLine(int length, const std::string& left, const std::string& middle, const std::string& right) {
std::string line = left;
for (int i = 0; i < length - 2; i++) {
line += middle;
}
line += right;
return line;
}
void drawInterface() {
getTerminalSize();
clearScreen();
int row = 1;
int col = 1;
int width = terminal_width - 2;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "SYSTEM MONITOR", COLOR_BOLD + COLOR_GREEN);
std::string time_str = "Press 'q' to quit | Auto-refresh every 0.5s";
drawText(row, width - 1 - time_str.length(), time_str, COLOR_WHITE);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row += 2;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "System Information", COLOR_BOLD + COLOR_YELLOW);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Hostname:", COLOR_WHITE);
drawText(row, col + 12, hostname, COLOR_GREEN);
drawText(row, col + 30, "Kernel:", COLOR_WHITE);
drawText(row, col + 38, kernelVersion, COLOR_GREEN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Uptime:", COLOR_WHITE);
drawText(row, col + 10, formatUptime(uptime_seconds), COLOR_GREEN);
drawText(row, col + 30, "Load Avg:", COLOR_WHITE);
std::ostringstream loadStr;
loadStr << std::fixed << std::setprecision(2) << load_avg_1min << ", "
<< load_avg_5min << ", " << load_avg_15min;
drawText(row, col + 40, loadStr.str(), COLOR_YELLOW);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Public IP:", COLOR_WHITE);
drawText(row, col + 13, publicIP, publicIP == "N/A (offline)" ? COLOR_RED : COLOR_CYAN);
drawText(row, col + 30, "Processes:", COLOR_WHITE);
drawText(row, col + 41, std::to_string(total_processes) + " total", COLOR_WHITE);
drawText(row, col + 52, std::to_string(running_processes) + " running", COLOR_GREEN);
row++;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row += 2;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "CPU Usage (per core)", COLOR_BOLD + COLOR_YELLOW);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
for (size_t i = 0; i < coreUsage.size() && i < 16; i++) {
if (row >= terminal_height - 25) break;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Core " + std::to_string(i) + ":", COLOR_WHITE);
std::string color = COLOR_GREEN;
if (coreUsage[i] > 75) color = COLOR_RED;
else if (coreUsage[i] > 50) color = COLOR_YELLOW;
std::ostringstream percent;
percent << std::fixed << std::setprecision(1) << std::setw(6) << coreUsage[i] << "%";
drawText(row, col + 10, percent.str(), color);
drawProgressBar(row, col + 20, 50, coreUsage[i], color);
row++;
}
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row += 2;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Memory Usage", COLOR_BOLD + COLOR_YELLOW);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "RAM:", COLOR_WHITE);
std::ostringstream memStr;
memStr << std::fixed << std::setprecision(1) << std::setw(6) << memUsed << " MB / "
<< std::setw(6) << memTotal << " MB";
drawText(row, col + 10, memStr.str(), COLOR_GREEN);
drawProgressBar(row, col + 35, 30, memPercent, COLOR_BLUE);
std::ostringstream memPercentStr;
memPercentStr << std::fixed << std::setprecision(1) << memPercent << "%";
drawText(row, col + 68, memPercentStr.str(), COLOR_WHITE);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Swap:", COLOR_WHITE);
std::ostringstream swapStr;
swapStr << std::fixed << std::setprecision(1) << std::setw(6) << swapUsed << " MB / "
<< std::setw(6) << swapTotal << " MB";
drawText(row, col + 10, swapStr.str(), COLOR_GREEN);
drawProgressBar(row, col + 35, 30, swapPercent, COLOR_MAGENTA);
std::ostringstream swapPercentStr;
swapPercentStr << std::fixed << std::setprecision(1) << swapPercent << "%";
drawText(row, col + 68, swapPercentStr.str(), COLOR_WHITE);
row++;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row += 2;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Disk Usage", COLOR_BOLD + COLOR_YELLOW);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Device", COLOR_WHITE);
drawText(row, col + 12, "Mount", COLOR_WHITE);
drawText(row, col + 25, "Type", COLOR_WHITE);
drawText(row, col + 35, "Used/Total", COLOR_WHITE);
drawText(row, col + 55, "Usage", COLOR_WHITE);
drawText(row, col + 70, "Read", COLOR_WHITE);
drawText(row, col + 85, "Write", COLOR_WHITE);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
for (size_t i = 0; i < diskInfo.size() && i < 6; i++) {
if (row >= terminal_height - 10) break;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, diskInfo[i].device, COLOR_CYAN);
std::string mount = diskInfo[i].mount_point;
if (mount.length() > 10) mount = "..." + mount.substr(mount.length() - 8);
drawText(row, col + 12, mount, COLOR_WHITE);
drawText(row, col + 25, diskInfo[i].fstype, COLOR_YELLOW);
std::ostringstream diskStr;
diskStr << formatDiskSize(diskInfo[i].used) << " / " << formatDiskSize(diskInfo[i].total);
drawText(row, col + 35, diskStr.str(), COLOR_GREEN);
std::string diskColor = COLOR_GREEN;
if (diskInfo[i].usage_percent > 90) diskColor = COLOR_RED;
else if (diskInfo[i].usage_percent > 75) diskColor = COLOR_YELLOW;
drawProgressBar(row, col + 55, 12, diskInfo[i].usage_percent, diskColor);
std::ostringstream readStr;
readStr << "↓ " << formatSize(diskInfo[i].read_speed) << "/s";
drawText(row, col + 70, readStr.str(), COLOR_GREEN);
std::ostringstream writeStr;
writeStr << "↑ " << formatSize(diskInfo[i].write_speed) << "/s";
drawText(row, col + 85, writeStr.str(), COLOR_RED);
row++;
}
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row += 2;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Network Interfaces", COLOR_BOLD + COLOR_YELLOW);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Interface", COLOR_WHITE);
drawText(row, col + 20, "IP Address", COLOR_WHITE);
drawText(row, col + 45, "MAC Address", COLOR_WHITE);
drawText(row, col + 70, "Download", COLOR_WHITE);
drawText(row, col + 85, "Upload", COLOR_WHITE);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
for (std::map<std::string, NetworkInterface>::iterator it = networkInterfaces.begin();
it != networkInterfaces.end(); ++it) {
if (row >= terminal_height - 5) break;
const NetworkInterface& iface = it->second;
drawText(row, col, BOX_V, COLOR_CYAN);
std::string iface_display = iface.name;
if (iface.is_wifi) iface_display += " (WiFi)";
drawText(row, col + 2, iface_display, iface.is_wifi ? COLOR_GREEN : COLOR_CYAN);
drawText(row, col + 20, iface.ip, COLOR_YELLOW);
drawText(row, col + 45, iface.mac, COLOR_WHITE);
std::ostringstream downStr;
downStr << "↓ " << formatSize(iface.rx_speed) << "/s";
drawText(row, col + 70, downStr.str(), COLOR_GREEN);
std::ostringstream upStr;
upStr << "↑ " << formatSize(iface.tx_speed) << "/s";
drawText(row, col + 85, upStr.str(), COLOR_RED);
row++;
}
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row += 2;
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "Top Processes (by CPU)", COLOR_BOLD + COLOR_YELLOW);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "PID", COLOR_WHITE);
drawText(row, col + 12, "Name", COLOR_WHITE);
drawText(row, col + 40, "CPU%", COLOR_WHITE);
drawText(row, width - 1, BOX_V, COLOR_CYAN);
row++;
int procCount = 0;
for (std::vector<std::tuple<double, std::string, std::string>>::iterator it = processList.begin();
it != processList.end() && procCount < 8 && row < terminal_height - 2; ++it, ++procCount) {
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, std::get<1>(*it), COLOR_YELLOW);
std::string name = std::get<2>(*it);
if (name.length() > 25) name = name.substr(0, 22) + "...";
drawText(row, col + 12, name, COLOR_WHITE);
std::ostringstream cpuStr;
cpuStr << std::fixed << std::setprecision(1) << std::setw(6) << std::get<0>(*it) << "%";
drawText(row, col + 40, cpuStr.str(), COLOR_GREEN);
row++;
}
while (procCount < 8 && row < terminal_height - 2) {
drawText(row, col, BOX_V, COLOR_CYAN);
drawText(row, col + 2, "", COLOR_WHITE);
row++;
procCount++;
}
drawText(row, col, makeHorizontalLine(width, "+", "-", "+"), COLOR_CYAN);
std::cout.flush();
}
bool kbhit() {
struct timeval tv = { 0L, 0L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
return select(1, &fds, NULL, NULL, &tv) > 0;
}
char getch() {
char buf = 0;
struct termios old;
if (tcgetattr(0, &old) < 0) return 0;
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0) return 0;
if (read(0, &buf, 1) < 0) buf = 0;
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
tcsetattr(0, TCSADRAIN, &old);
return buf;
}
public:
SystemMonitor() : running(true), terminal_width(120), terminal_height(35),
total_processes(0), running_processes(0),
load_avg_1min(0), load_avg_5min(0), load_avg_15min(0) {
}
bool initialize() {
if (!isatty(STDOUT_FILENO)) {
std::cerr << "Error: Must be run in a terminal" << std::endl;
return false;
}
tcgetattr(STDIN_FILENO, &orig_termios);
updateHostname();
updateKernelVersion();
updateUptime();
updateLoadAverage();
updatePublicIP();
prevCores = readCPUStats();
updateNetworkInterfaces();
updateDiskInfo();
updateProcessInfo();
hideCursor();
return true;
}
void run() {
auto lastUpdate = std::chrono::steady_clock::now();
auto lastIPUpdate = std::chrono::steady_clock::now();
while (running) {
auto now = std::chrono::steady_clock::now();
if (now - lastUpdate >= std::chrono::milliseconds(500)) {
updateCPUUsage();
updateMemoryInfo();
updateLoadAverage();
updateNetworkInterfaces();
updateUptime();
updateProcessInfo();
updateDiskInfo();
drawInterface();
lastUpdate = now;
}
if (now - lastIPUpdate >= std::chrono::seconds(60)) {
updatePublicIP();
lastIPUpdate = now;
}
if (kbhit()) {
char c = getch();
if (c == 'q' || c == 'Q') {
running = false;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
showCursor();
clearScreen();
std::cout << "System monitor stopped." << std::endl;
}
~SystemMonitor() {
tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios);
showCursor();
}
};
int main(int argc, char* argv[]) {
if (geteuid() != 0) {
std::cout << "\033[33mWarning: Not running as root. Some information may be limited.\033[0m" << std::endl;
std::cout << "Consider running with: sudo " << argv[0] << std::endl;
sleep(2);
}
SystemMonitor monitor;
if (!monitor.initialize()) {
std::cerr << "Failed to initialize system monitor" << std::endl;
return 1;
}
monitor.run();
return 0;
}