— Scoopta 4 months ago
External now runs scripts in a separate thread to prevent them from lagging the bar thread
1 files changed, 42 insertions(+), 18 deletions(-)

M plugins/external.c
M plugins/external.c +42 -18
@@ 17,17 17,56 @@
  #include <map.h>
 #include <stdio.h>
+#include <utils.h>
 #include <unistd.h>
+#include <pthread.h>
 
-static const char* arg_names[] = {"exec"};
+static const char* arg_names[] = {"exec", "interval"};
 
 struct external {
 	const char* exec;
+	char* ret;
+	time_t interval;
 };
 
+static void* poll(void* data) {
+	struct external* this = data;
+	while(true) {
+		if(this->exec == NULL) {
+			fprintf(stderr, "That's not a valid executable\n");
+			goto sleep;
+		}
+		if(access(this->exec, X_OK) == 0) {
+			FILE* proc = popen(this->exec, "r");
+			char* line = NULL;
+			size_t line_s = 0;
+			ssize_t line_l = getline(&line, &line_s, proc);
+			line[line_l - 1] = 0;
+			pclose(proc);
+			if(this->ret != NULL) {
+				free(this->ret);
+			}
+			this->ret = strdup(line);
+			free(line);
+		} else {
+			fprintf(stderr, "%s cannot be found\n", this->exec);
+		}
+		sleep:
+		utils_sleep_millis(this->interval);
+	}
+	return NULL;
+}
+
 void* external_init(struct map* props) {
-	struct external* this = malloc(sizeof(struct external));
+	struct external* this = calloc(1, sizeof(struct external));
 	this->exec = strdup(map_get(props, "exec"));
+	const char* interval = map_get(props, "interval");
+	if(interval == NULL) {
+		interval = "1000";
+	}
+	this->interval = strtol(interval, NULL, 10);
+	pthread_t thread;
+	pthread_create(&thread, NULL, poll, this);
 	return this;
 }
 

          
@@ 41,21 80,6 @@
  void external_get_info(void* data, const char* format, char* out, size_t size) {
 	struct external* this = data;
-	if(this->exec == NULL) {
-		fprintf(stderr, "That's not a valid executable\n");
-		return;
-	}
-	if(access(this->exec, X_OK) == 0) {
-		FILE* proc = popen(this->exec, "r");
-		char* line = NULL;
-		size_t line_s = 0;
-		ssize_t line_l = getline(&line, &line_s, proc);
-		line[line_l - 1] = 0;
-		pclose(proc);
-		snprintf(out, size, format, line);
-		free(line);
-	} else {
-		fprintf(stderr, "%s cannot be found\n", this->exec);
-	}
+	snprintf(out, size, format, this->ret);
 }