1 chardev.c
#include <linux/module.h>
#include <linux/kernel.h>#include <linux/init.h>
#include <linux/fs.h>
#define MYMAJOR 200
#define MYNAME "chardev"
static int test_chardev_open(struct inode *inode,struct file *file)
{
printk(KERN_INFO "test chardev_open\n");
return 0;
}
static int test_chardev_release(struct inode *inode,struct file *file){
printk(KERN_INFO "test chardev_relase\n");
return 0;
}
static const struct file_operations test_fops={
.owner=THIS_MODULE,
.open=test_chardev_open,
.release=test_chardev_release,
};
static int __init chardev_init(void)
{ int ret=-1;
printk(KERN_INFO "jimmy module chardev init");
ret=register_chrdev(MYMAJOR,MYNAME,&test_fops);
if(ret)
{
printk(KERN_ERR "register_chrdev fail\n");
return -EINVAL;
}
printk(KERN_INFO "register_chrdev success...\n");
return 0;
}
static void __exit chardev_exit(void)
printk(KERN_INFO "jimmy module chardev exit\n");
unregister_chrdev(MYMAJOR, MYNAME);
}
module_init(chardev_init);
module_exit(chardev_exit);
// MODULE_xxx這種宏作用是用來添加模塊描述信息
MODULE_LICENSE("GPL"); // 描述模塊的許可證
MODULE_AUTHOR("aston"); // 描述模塊的作者
MODULE_DESCRIPTION("module test"); // 描述模塊的介紹信息
MODULE_ALIAS("alias xxx"); // 描述模塊的別名信息
2. app.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FILE "/dev/chardev" // mknod /dev/chardev c 2000 只要主設備號和驅動裏定義的一樣就可,名字可以和驅動裏的MYNAME不同
int main(void)
{
int fd = -1;
fd = open(FILE, O_RDWR);
if (fd < 0)
{
printf("open %s error.\n", FILE);
return -1;
}
printf("open %s success..\n", FILE);
close(fd);
return 0;
}
3. Makefile
#ubuntu的內核源碼樹,如果要編譯在ubuntu中安裝的模塊就打開這2個
#KERN_VER = $(shell uname -r)
#KERN_DIR = /lib/modules/$(KERN_VER)/build
# 開發板的linux內核的源碼樹目錄
KERN_DIR = /arm/s5pv210/kernel
obj-m += chardev.o
all:
make -C $(KERN_DIR) M=`pwd` modules
arm-none-linux-gnueabi-gcc app.c -o app -static // static編譯,否則執行時會報錯 " ./app not found"
cp:
cp *.ko /arm-nfs/jimmy_test
cp app /arm-nfs/jimmy_test
.PHONY: clean
clean:
make -C $(KERN_DIR) M=`pwd` modules clean