Last active
August 29, 2015 14:04
-
-
Save jepio/1ed9d85b7c2fea3f6429 to your computer and use it in GitHub Desktop.
A daemon to show notification if battery is low.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <libnotify/notify.h> | |
#define LIMIT 20 | |
/* | |
* Make a notification popup with the current battery status. | |
* From: | |
* https://wiki.archlinux.org/index.php/Desktop_notifications#Usage_in_programming | |
*/ | |
void notify(int cap) | |
{ | |
char c[100]; | |
notify_init("Battery"); | |
sprintf(c, "Battery is at %d", cap); | |
NotifyNotification *batt = | |
notify_notification_new("Battery", c, "battery-low"); | |
notify_notification_show(batt, NULL); | |
g_object_unref(G_OBJECT(batt)); | |
notify_uninit(); | |
} | |
int main(void) | |
{ | |
/* | |
* Fork process, detach from terminal and background - basically turn it | |
* into a daemon. | |
* Alternative to using daemon is doing everything from: | |
* http://www.thegeekstuff.com/2012/02/c-daemon-process/ | |
*/ | |
int ret = daemon(0, 0); | |
if (ret < -1) { | |
printf("Daemon failed\n"); | |
exit(1); | |
} | |
/* | |
* Create PID file - only works as root. Libnotify however, does not | |
* work as root. | |
*/ | |
FILE *fp; | |
pid_t pid = getpid(); | |
fp = fopen("/var/run/battery.pid", "w"); | |
if (fp != NULL) { | |
fprintf(fp, "%d\n", pid); | |
fclose(fp); | |
} | |
/* Check battery capacity, notify if low and sleep 1 minute. */ | |
while (true) { | |
int cap = 0; | |
fp = fopen("/sys/class/power_supply/BAT1/capacity", "r"); | |
if (fp == NULL) | |
goto rest; | |
fscanf(fp, "%d", &cap); | |
if (cap < LIMIT) | |
notify(cap); | |
fclose(fp); | |
rest: | |
sleep(60); | |
} | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CC = gcc | |
NOTIFY += $(shell pkg-config --cflags --libs libnotify) | |
.PHONY: clean | |
battery_daemon: battery_daemon.c | |
$(CC) -o $@ $(NOTIFY) $(CFLAGS) $< | |
clean: | |
rm -rf battery_daemon |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To kill the daemon check what PID it has with:
ps -ax | grep battery_daemon
and then
kill
that PID.