From: Armaan Bhojwani Date: Sat, 10 Apr 2021 23:49:54 +0000 (-0400) Subject: tides: new program, simple fetch program X-Git-Tag: v0.0.1~2 X-Git-Url: https://git.armaanb.net/?p=bin.git;a=commitdiff_plain;h=b510e2b26e17ea765afe6ae164d482982a63053a tides: new program, simple fetch program Preliminary version of a simple fetch program. Mostly for learning C and the Linux APIs. --- diff --git a/.gitignore b/.gitignore index 0993049..b307a43 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *cache* bin +a.out diff --git a/tides.c b/tides.c new file mode 100644 index 0000000..d1eba77 --- /dev/null +++ b/tides.c @@ -0,0 +1,56 @@ +// Yet another (tm) fetch program + +#include +#include +#include +#include + +#include +#include +#include + +int +main(void) +{ + // Get hostname + char hostname[HOST_NAME_MAX]; + gethostname(hostname, HOST_NAME_MAX); + + // Get username + char username[LOGIN_NAME_MAX]; + getlogin_r(username, LOGIN_NAME_MAX); + + // Get kernel info + struct utsname kernel; + uname(&kernel); + + // Get assorted system info + struct sysinfo info; + sysinfo(&info); + + /* Get memory info from /proc. Inspired by busybox free.c, which is + GPLv2 licensed */ + char buf[60]; // actual lines we expect are ~30 chars or less + int counter = 2; // Number of things being scanned for in the file + unsigned long total_kb, avail_kb; + + FILE *fp = fopen("/proc/meminfo", "r"); + total_kb = avail_kb = 0; + while (fgets(buf, sizeof(buf), fp)) { + if (sscanf(buf, "MemTotal: %lu %*s\n", &total_kb) == 1) + if (--counter == 0) + break; + if (sscanf(buf, "MemAvailable: %lu %*s\n", &avail_kb) == 1) + if (--counter == 0) + break; + } + fclose(fp); + + // Display + printf("%s@%s\n", username, hostname); + printf("%s %s\n", kernel.sysname, kernel.release); + struct tm *uptime = gmtime(&info.uptime); + printf("Up %02dh %02dm %02ds\n", uptime->tm_hour, uptime->tm_min, + uptime->tm_sec); + printf("%0.0f/%0.0f MB RAM\n", (total_kb - avail_kb)/1024.0, total_kb/1024.0); +}