Skip to content

Instantly share code, notes, and snippets.

@robbmanes
Created September 8, 2016 14:30
Show Gist options
  • Save robbmanes/4b4dbb22271bed3e5e61fb5b8afd9dd3 to your computer and use it in GitHub Desktop.
Save robbmanes/4b4dbb22271bed3e5e61fb5b8afd9dd3 to your computer and use it in GitHub Desktop.
Half Day Linux Kernel Module, shows usage of timers in kernel fairly well but otherwise useless
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/time.h>
#include <linux/timer.h>
#define TEN_SECS_IN_MS 10000
#define WORK_BEFORE 1473336000
#define WORK_AFTER 1473350400
static int robbb_mod_workflag = 0;
static struct timer_list robbb_mod_timer;
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Robb Manes");
MODULE_DESCRIPTION("Robb is taking a half day.");
MODULE_VERSION("0.1");
static int __init half_day_init(void);
void robbb_timer_callback(unsigned long data);
static void __exit half_day_exit(void);
static int __init half_day_init(void)
{
int ret = 0;
printk("Registering Robb's half day module...\n");
setup_timer(&robbb_mod_timer, robbb_timer_callback, 0);
ret = mod_timer(&robbb_mod_timer, jiffies + msecs_to_jiffies(10));
if(ret)
printk("Unable to load timer robbb_mod_timer!\n");
return 0;
}
void robbb_timer_callback(unsigned long data)
{
struct timeval tv;
do_gettimeofday(&tv);
/* Todo - convert and print local times based on epoch in &tv */
if((WORK_BEFORE >= tv.tv_sec))
{
printk("Robb is currently not working yet!\n");
}
else if((WORK_BEFORE <= tv.tv_sec) && (WORK_AFTER >= tv.tv_sec))
{
printk("Robb is currently at work!\n");
}
else if(WORK_AFTER <= tv.tv_sec)
{
printk("Robb has left work, and taken his half day!\n");
robbb_mod_workflag = 1;
}
if(!robbb_mod_workflag)
mod_timer(&robbb_mod_timer, jiffies + msecs_to_jiffies(TEN_SECS_IN_MS));
}
static void __exit half_day_exit(void)
{
printk("Unloading robbb's half-day module...\n");
if(del_timer(&robbb_mod_timer))
printk("Timer still in use, unable to delete robbb_mod_timer.\n");
return;
}
module_init(half_day_init);
module_exit(half_day_exit);
obj-m += robbbmod_sept_7.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment