驱动代码
#include #include #include #include #include #include #include #define MY_DEVICE_NAME "mydevice" #define MY_DEVICE_MAJOR 240 int device_open(struct inode * inode,struct file *flip) { int num=MINOR(inode->i_rdev); printk("My device open ->minor: %d/n",num); return 0; } ssize_t device_read(struct file * filp,char * buf,size_t count,loff_t *f_ops ) { printk("My device read ->buf : %08X count %08X/n",buf,count); return 0; } ssize_t device_write(struct file * filp,const char * buf,size_t count,loff_t *f_ops) { printk("My device wirte ->buf : %08X count %08X/n",buf,count); return 0; } int device_close(struct inode *inode,struct file *flip) { printk("My device close/n"); return 0; } struct file_operations my_device_fops = { .owner=THIS_MODULE, .read=device_read, .open=device_open, .write=device_write, .release=device_close, }; int mydevice_init(void) { int ret; printk("call my device/n"); ret=register_chrdev(MY_DEVICE_MAJOR,MY_DEVICE_NAME,&my_device_fops); if(ret<0) { printk("Regist device error/n"); return ret; } return 0; } void mydevice_exit(void) { printk("call my device release/n"); unregister_chrdev(MY_DEVICE_MAJOR,MY_DEVICE_NAME); } module_init (mydevice_init); module_exit(mydevice_exit); MODULE_LICENSE("Dual BSD/GPL");
Makefile文件
#KVER = /usr/src/linux-source-2.6.38
KVER = /lib/modules/`uname -r`/build
CURDIR = $(shell pwd)
# Kernel modules
obj-m := my_device.o
build: kernel_modules
kernel_modules:
$(MAKE) -C $(KVER) M=$(CURDIR) modules
clean:
$(MAKE) -C $(KVER) M=$(CURDIR) clean
测试代码
#include #include #include #include #include #include #define DEVICE_NAME "/dev/yming_device" int main() { int dev; int ret; dev=open(DEVICE_NAME,O_RDWR|O_NDELAY); printf("dev : %d/n",dev); if(dev<0) { printf("can not open the device %s/n",DEVICE_NAME); return -1; } read(dev,0x30,0x31); write(dev,0x41,0x42); close(dev); printf("the program is over/n"); return 0; }
然后gcc call_test.c -o call_test
sudo insmod#加载驱动
然后创建字符设备
sudo mknod /dev/yming_device c 240 32
分别表示设备文件名,设备类型,主设备号,次设备号
运行call_test,然后使用命令查看驱动的运行信息
dmesg | tail
如下
[ 1190.544602] keyboard: can't emulate rawmode for keycode 240
[ 1190.544620] keyboard: can't emulate rawmode for keycode 240
[ 1521.351828] exe (1755): /proc/1755/oom_adj is deprecated, please use /proc/1755/oom_score_adj instead.
[ 6359.871814] call my device
[ 7014.893799] call my device release
[ 7283.765009] call my device
[ 7289.153601] My device open ->minor: 32
[ 7289.153663] My device read ->buf : 00000030 count 00000031
[ 7289.153667] My device wirte ->buf : 00000041 count 00000042
[ 7289.153671] My device close
注,注意应用程序对设备的操作权限,可以使用命令
chmod 777 /dev/yming_device 给所有用户以读写权限