使用命令建立一个设备 s 驱动代码
#include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/cdev.h> #include <linux/major.h> static ssize_t flash_env_dev_open(struct inode *inode,struct file *file) { return 0; } static ssize_t flash_env_dev_read(struct file *file, char __user buf, size_t count, loff_t *ppos) { return 0; } static ssize_t flash_env_dev_ioctl(struct inode *inode,struct file *file,unsigned int cmd,unsigned long arg) { printk("<1> %dn",cmd); switch(cmd){ case 0: printk("<1> in flash 0n"); break; case 1: printk("<1> in flash 1n"); break; default: printk("<1> othersn"); } return 0; } static const struct file_operations flash_fops = { .owner =THIS_MODULE, .open = flash_env_dev_open, .read = flash_env_dev_read, .ioctl = flash_env_dev_ioctl, }; #define MAX_FLASH_ENV_MINORS 262 static struct cdev flash_cdev; dev_t dev; static __init int flash_env_dev_init(void) { int res; dev=MKDEV(263,262); cdev_init(&flash_cdev,&flash_fops); res=register_chrdev_region(dev, MAX_FLASH_ENV_MINORS, "/dev/env_dev"); if(res) printk("<1> fuckn"); res=cdev_add(&flash_cdev,dev,MAX_FLASH_ENV_MINORS); if(res) printk("<1> fuck2 n"); /* devfs_mk_dir("flash_env_dev");*/ printk("<1> Hello Worldn"); return 0; } static void __exit flash_env_dev_exit(void) { unregister_chrdev_region(dev,MAX_FLASH_ENV_MINORS); printk("<1> exit Hello Worldn"); } module_init(flash_env_dev_init); module_exit(flash_env_dev_exit); |
---|
下面是建立设备
mknod -m 666 /dev/env_dev c 263 262 |
---|
然后写个makefile
KERNELDIR = /usr/src/kernels/2.6.27.25-170.2.72.fc10.i686 PWD := $(shell pwd) obj-m := chrdev.o modules: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules gcc test_chrdev.c -o test_chrdev clean: rm -rf *.o *.ko test_chrdev Module.* module* *.mod.c |
---|
然后写个测试程序
KERNELDIR = /usr/src/kernels/2.6.27.25-170.2.72.fc10.i686 PWD := $(shell pwd) obj-m := chrdev.o modules: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules gcc test_chrdev.c -o test_chrdev clean: rm -rf *.o *.ko test_chrdev Module.* module* *.mod.c |
---|