代码: 全选
#include <linux/init.h>
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <asm/uaccess.h>
#include <linux/fs.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("zhangn1985@gmail.com");
#define DEVICE_NAME "mychrdev"
#define NUM 8
char men[NUM];
int lenth=0;
static struct mutex mutex;
ssize_t my_write(struct file *fp, const char __user *buf,size_t count,loff_t *offp){
int i=(NUM>=count)?count:NUM;
mutex_lock(&mutex);
copy_from_user(men,buf,i);
lenth=i;
printk (KERN_ALERT "men is %s",men);
printk (KERN_ALERT "lenth is %d",lenth);
mutex_unlock(&mutex);
return i;
}
ssize_t my_read(struct file *fp, char __user *buf,size_t count,loff_t *offp){
int i=(NUM>=count)?count:NUM;
mutex_lock(&mutex);
+ if(*offp >= lenth) {
+ goto FALL;
+ }
i=(lenth>=i)?i:lenth;
copy_to_user(buf,men,i);
+ *offp+=i;
mutex_unlock(&mutex);
return i;
+ FALL:
+ mutex_unlock(&mutex);
+ return 0;
}
static int my_open(struct inode *inod, struct file *fp){
if (!try_module_get(THIS_MODULE))return -EBUSY;
return 0;
}
static int my_release(struct inode *inod,struct file *fp){
module_put(THIS_MODULE);
return 0;
}
static struct file_operations fileop={
.read = my_read,
.write = my_write,
.open = my_open,
.release = my_release,
};
static struct cdev *dev;
static dev_t devt;
static int my_init(void){
int ret;
printk(KERN_ALERT "mymodule init...\n");
if ((ret=alloc_chrdev_region(&devt,0,1,DEVICE_NAME))<0){
printk(DEVICE_NAME "\ncan't register major number");
return ret;
}else{
printk(KERN_ALERT "mymodule get majmun %d\n",MAJOR(devt));
}
if ((dev=cdev_alloc())==NULL){
printk(DEVICE_NAME "\ncdev_alloc error");
ret=-1;
goto FALL1;
}
cdev_init(dev,&fileop);
if ((ret=cdev_add(dev,devt,1))<0){
printk(DEVICE_NAME "\ncdev_add error");
goto FALL2;
}
mutex_init(&mutex);
return 0;
FALL2:
cdev_del(dev);
FALL1:
unregister_chrdev_region(devt,1);
return ret;
}
static void my_exit(void){
printk (KERN_ALERT "mymodule exit...\n");
cdev_del(dev);
unregister_chrdev_region(devt,1);
mutex_destroy(&mutex);
}
module_init(my_init);
module_exit(my_exit);
代码: 全选
obj-m := mychrdev.o
KERNELDIR:=/lib/modules/$(shell uname -r)/build
PWD:=$(shell pwd)
default:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:
rm *.o;rm *.ko
在kern.log中模块会打印自己的主设备号,或者从/proc/modules中看这个设备的设备号major,设备名为mychrdev
一般分配成250 //真杯具
用mknod /dev/NAME_YOU_WANT c $major 0 生成设备节点。
用echo xxxxx > /dev/NAME_YOU_WANT 写入
用cat /dev/NAME_YOU_WANT 读出