2014年7月2日 星期三

[Kernel Module] My first Kernel Module




Kernel Code 1


#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
static ssize_t drv_read(struct file *filp, char *buf, size_t count, loff_t *ppos)
{
printk
("device read\n");
return count;
}

static ssize_t drv_write(struct file *filp, const char *buf, size_t count, loff_t *ppos)
{
printk
("device write \n");
return count;
}

static int drv_open(struct inode *inode, struct file *filp)
{
printk
("device open \n");
return 0;
}


int drv_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg)
{
printk
("device ioctl \n");
return 0;
}

static int drv_release(struct inode *inode, struct file *filp)
{
printk
("device close \n");
return 0;
}

struct file_operations drv_fops =
{
read
: drv_read,
write
: drv_write,
compat_ioctl
: drv_ioctl,
open
: drv_open,
release
: drv_release,
};

#define MAJOR_NUM 60
#define MODULE_NAME "DEMO"
static int demo_init(void) {
if (register_chrdev(MAJOR_NUM, "demo", &drv_fops) < 0) {
printk
("<1>%s: can't get major %d\n", MODULE_NAME, MAJOR_NUM);
return (-EBUSY);
}

printk
("<1>%s:started\n", MODULE_NAME);
return 0;
}

static void demo_exit(void) {
unregister_chrdev
(MAJOR_NUM, "demo");
printk
("<1>%s: removed\n", MODULE_NAME);
}

module_init
(demo_init);
module_exit
(demo_exit);


Compile Kernel Module


make -C /lib/modules/3.8.0-33-generic/build M=`pwd` test.ko


User Space Code


#include <stdio.h>
int main()
{
char buf[512];
FILE
*fp = fopen("/dev/demo", "w+");
if(fp == NULL) {
printf
("can't open device!\n");
return 0;
}
fread
(buf, sizeof(buf), 1, fp);
fwrite
(buf, sizeof(buf), 1, fp);
fclose
(fp);
return 0;
}


Compile User Space Code


gcc test.c


Execute Code


sudo ./a.out


Result


tail -n 10 /var/log/kern.log
Jul 3 12:14:36 happy-Desktop kernel: [12404.120783] device close
Jul 3 12:14:37 happy-Desktop kernel: [12405.044410] device open
Jul 3 12:14:37 happy-Desktop kernel: [12405.044447] device read
Jul 3 12:14:37 happy-Desktop kernel: [12405.044477] device close
Jul 3 12:14:38 happy-Desktop kernel: [12406.056777] device open
Jul 3 12:14:38 happy-Desktop kernel: [12406.056814] device read
Jul 3 12:14:38 happy-Desktop kernel: [12406.056839] device close
Jul 3 12:15:10 happy-Desktop kernel: [12438.189191] device open
Jul 3 12:15:10 happy-Desktop kernel: [12438.189233] device read
Jul 3 12:15:10 happy-Desktop kernel: [12438.189262] device close


0 意見:

張貼留言