一.字符设备驱动基础框架:
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#define CHRDEVBASE_MAJOR 200
#define CHRDEVBASE_NAME "chrdevbase"
static int chrdevbase_open(struct inode *inode, struct file *filp)
{
printk("chrdevbase open!\r\n");
return 0;
}
static ssize_t chrdevbase_read(struct file *filp, char __user *buf, size_t cnt, loff_t *offt)
{
printk("chrdevbase read!\r\n");
return 0;
}
static ssize_t chrdevbase_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
{
printk("chrdevbase write!\r\n");
return 0;
}
static int chrdevbase_release(struct inode *inode, struct file *filp)
{
printk("chrdevbase release!\r\n");
return 0;
}
static struct file_operations chrdevbase_fops = {
.owner = THIS_MODULE,
.open = chrdevbase_open,
.read = chrdevbase_read,
.write = chrdevbase_write,
.release = chrdevbase_release,
};
static int __init chrdevbase_init(void)
{
int ret=0;
int retvalue = 0;
printk("chrdevbase_init\r\n");
retvalue = register_chrdev(CHRDEVBASE_MAJOR, CHRDEVBASE_NAME, &chrdevbase_fops);
if(retvalue < 0)
{
printk("register chrdevbase error!\r\n");
}
return ret;
}
static void __exit chrdevbase_exit(void)
{
unregister_chrdev(CHRDEVBASE_MAJOR,CHRDEVBASE_NAME);
printk("chrdevvase_exit\r\n");
}
module_init(chrdevbase_init);
module_exit(chrdevbase_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("LeeJiEun");
MODULE_INFO(intree,"Y");
二.应用程序:
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
int main(int argc, char *argv[])
{
int fd;
char *filename;
if(argc != 2)
{
printf("args error!\r\n");
return -1;
}
filename = argv[1];
fd = open(filename, O_RDWR);
if(fd==-1)
{
perror("open error");
return -1;
}
close(fd);
if(fd==-1)
{
perror("close error");
return -1;
}
return 0;
}
最终效果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/197ed427cec7be2ee4c8dea220d738b3.png#pic_center)