|
小弟想撰写一个虚拟的字符设备模块,设想cat设备文件时能显示"Hi,Everyone!"。以下是代码,编译能够通过,并且顺利挂载了设备文件,但是cat的时候却显示"cat: /dev/mdev: 没有那个设备或者地址",能否指点其中迷津?谢谢!
- #<linux/init.h>
- #include <linux/module.h>
- #include <linux/fs.h>
- #include <linux/kdev_t.h>
- #include <linux/cdev.h>
- #include <asm/uaccess.h>
- static dev_t dev_num;
- static struct cdev chardev;
- ssize_t dev_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) {
- if (copy_to_user(buf, "Hi, everyone!", 14)) {
- printk (KERN_ALERT "Read part!");
- return 12;
- }
- printk(KERN_ALERT "Read whole!");
- return 0;
- }
- int dev_open(struct inode *inode, struct file *filp) {
- return 0;
- }
- struct file_operations fops = {
- .owner = THIS_MODULE,
- .read = dev_read,
- .open = dev_open,
- };
- static int __init dev_init(void)
- {
- if (alloc_chrdev_region(&dev_num,0,1,"dev1")<0){
- printk(KERN_ALERT "Error in allocating Device Number!");
- return -1;
- }
- cdev_init(&chardev,&fops);
- chardev.owner = THIS_MODULE;
- chardev.ops = &fops;
- if (cdev_add(&chardev,dev_num,1) < 0) {
- printk(KERN_ALERT "Error in adding cdev structure!");
- return -1;
- }
- printk (KERN_ALERT "Succeed in adding cdev!");
- printk(KERN_ALERT "Hello, device is on!");
- return 0;
- }
- static void dev_exit(void)
- {
- unregister_chrdev_region(dev_num,1);
- cdev_del(&chardev);
- printk(KERN_ALERT "Goodbye!");
- }
- module_init(dev_init);
- module_exit(dev_exit);
复制代码 |
|