Category Archives: My projects

C++ Hibernate Daemon

I use Fluxbox window manager on Ubuntu Linux where I don’t have all the bells and whistles of GNOME or KDE.

so I thought I’d make myself a daemon program that will automatically put my computer to hibernate when my laptop battery is almost empty

usually I take care that my battery doesn’t get to the red zone but this is for those few cases I forget

I wrote this small programm in C++

why c++

well because I don’t programm in c++ and I found it interesting to do so :)

main.cpp looks like this

so, you see the locations of the info and state file for the laptop battery, the percent at which we go to hibernation (I’ve set it to 12%), and the sleep interval before checking the battery state again (10 seconds)

I use my own hibernate script but you could use something like /usr/sbin/hibernate

you can change all of these

in the main function you can se that:

  • we work only as a root user
  • we daemonize (detach from the terminal and run in background)
  • instantiate a worker class object
  • and do our work :)

and what is our work? check out this picture

worker.cpp

well we get the battery total capacity and current capacity and then we calculate the percent

if the percent is less that what I want (12%) then I want my laptop to go to hibernaton

but I also made a security check (that you can remove if you like)

that makes sure my laptop doesn’t go twice into hibernation in succession

why did I do that?

well because I parse data from some files I have no influence over

and those files can change their format anytime

so this is just a precaution

I have a simple makefile that compiles this code, copies it to /usr/local/bin/medved (medved in my language means a bear and bears hibernate ;) ) and adds an entry to /etc/rc.local so that it starts next time you reboot your box automatically

you can also start it by hand and see how it works before the reboot

and that’s it, now I have a daemon that puts my laptop to hibernation before my battery runs dry

I’ve published the source code under GPL licence version 3

you can get source code here