- 论坛徽章:
- 0
|
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
MODULE_LICENSE("Dual BSD/GPL");
dev_t t_iDevNo = 0;
struct cdev *t_pDev = NULL;
static ssize_t Read(struct file *pFile, char __user *pUsr, size_t count, loff_t *pLoff)
{
printk("Read in myDev.\n");
return 0;
}
static ssize_t Write(struct file *pFile, const char __user *pUsr, size_t count, loff_t *pLoff)
{
printk("Write in myDev.\n");
return 0;
}
static int Open(struct inode *inode, struct file *file)
{
printk("Open in myDev.\n");
return 0;
}
static int Release(struct inode *inode, struct file *file)
{
printk("Release in myDev.\n");
return 0;
}
static int __init MyDriverInit(void)
{
int iRet = 0;
int iDevMajor = 0;
struct file_operations fileOps = {
.owner = THIS_MODULE,
.read = Read,
.write = Write,
.open = Open,
.release = Release
};
if(iDevMajor > 0) // 如果预设了有效值
{
t_iDevNo = MKDEV(iDevMajor, 0);
iRet = register_chrdev_region(t_iDevNo, 1, "MyDrv"); // 静态申请
}
else
{
iRet = alloc_chrdev_region(&t_iDevNo, 0, 1, "MyDrv"); // 动态申请
}
if(iRet >= 0)
{
t_pDev = cdev_alloc();
if(t_pDev != NULL)
{
kobject_set_name(&t_pDev->kobj, "MyDrv");
t_pDev->owner = THIS_MODULE;
t_pDev->ops = &fileOps;
t_pDev->dev = t_iDevNo;
t_pDev->count = 1;
cdev_init(t_pDev, t_pDev->ops);
iRet = cdev_add(t_pDev, t_iDevNo, 1);
if(iRet != 0)
{
printk(KERN_NOTICE"cdev_add fail.\n");
unregister_chrdev_region(t_iDevNo, 1);
}
}
else
{
printk(KERN_NOTICE"kmalloc fail.\n");
unregister_chrdev_region(t_iDevNo, 1);
}
}
else
{
printk(KERN_INFO"Can't get device number.\n");
}
printk(KERN_ALERT "Insert my driver.\n");
return iRet;
}
static void __exit MyDriverExit(void)
{
cdev_del(t_pDev);
unregister_chrdev_region(t_iDevNo, 1);
printk(KERN_ALERT "Remove my dirver.\n");
}
module_init(MyDriverInit);
module_exit(MyDriverExit);
编译后insmod MyDriver.ko,在/proc/devices/里看到是253,然后mknod /dev/MyDrv0 c 253 0
应用程序代码就
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int iDevId = open("/dev/MyDrv0", O_RDWR);
if(iDevId > 0)
{
close(iDevId);
}
else
{
printf("Can't open /dev/MyDrv0.\n");
}
return 0;
}
大多数时候一运行就卡住了,偶尔会执行完,但是Open()里加的打印,没见效果。
有经验的人士请不吝指点下,哪儿写错了? |
|