]> git.armaanb.net Git - bin.git/commitdiff
tides: new program, simple fetch program
authorArmaan Bhojwani <me@armaanb.net>
Sat, 10 Apr 2021 23:49:54 +0000 (19:49 -0400)
committerArmaan Bhojwani <me@armaanb.net>
Sat, 10 Apr 2021 23:49:54 +0000 (19:49 -0400)
Preliminary version of a simple fetch program. Mostly for learning C
and the Linux APIs.

.gitignore
tides.c [new file with mode: 0644]

index 099304959a1b0226e3b444507b7987040833a045..b307a43cf90546cb3009e0d071654be41a09900f 100644 (file)
@@ -1,2 +1,3 @@
 *cache*
 bin
+a.out
diff --git a/tides.c b/tides.c
new file mode 100644 (file)
index 0000000..d1eba77
--- /dev/null
+++ b/tides.c
@@ -0,0 +1,56 @@
+// Yet another (tm) fetch program
+
+#include <unistd.h>
+#include <sys/utsname.h> 
+#include <sys/sysinfo.h> 
+#include <time.h>
+
+#include <limits.h>
+#include <string.h>
+#include <stdio.h>
+
+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);
+}