编写自己的内核模块

#include <linux/module.h>
#include <linux/timer.h>
#include <linux/errno.h>
#include <linux/init.h>
static int sec = 5;
module_param(sec,int,S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(sec,"set the interval.");

static void mymod_timer(unsigned long data);
static DEFINE_TIMER(timer,mymod_timer,0,0);

static void mymod_timer(unsigned long data)
{
	printk("mymod: timer \n");
	mod_timer(&timer,jiffies + sec * HZ);
}

static int mymod_init(void)
{
	printk("mymod: init \n");
	if (sec <= 0)
	{
		printk(KERN_INFO,"Invalid interval sec = %d \n",sec);
		return -EINVAL;
	}
	mod_timer(&timer,jiffies + sec * HZ);
	return 0;
}

static void mymod_exit(void)
{
	printk("mymod: exit\n");
	del_timer(&timer);
}

module_init(mymod_init);
module_exit(mymod_exit);

MODULE_AUTHOR("db liu");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("my first module");

源文件保存为:mymod.c

编写Makefile文件:

obj-m := mymod.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

安装模块

    insmod mymod.ko

查看安装的模块

    lsmod | grep mymod

检查安装模块是否安装成功

    dmesg | tail

mymod: init

mymod: timer

卸载模块

    rmmod mymod

检查是否卸载成功

    dmesg | tail

mymod: exit

你可能感兴趣的:(dmesg,rmmod,insmod,内核模块编写,lsmod)