
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
【本文正在参与优质创作者激励】
老规矩还是将最终希望跑出来的效果如下:
@toc
这个看似不是问题的问题却很重要,我们必须需要从这一步开始理清楚,见下图:
写应用程序的目的主要是为了测试驱动程序,测试的方法为调用glibc的open、read、write函数。
代码见下:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
int fd;
char buf[1024];
int len;
int ret;
if (argc < 2) {
printf("Usage: %s -w <string>\n", argv[0]);
printf(" %s -r\n",argv[0]);
return -1;
}
fd = open("/dev/hello_linux_dri", O_RDWR);
if (fd == -1)
{
printf("can not open file /dev/hello_linux_dri\n");
return -1;
}
printf("open /dev/hello_linux_dri success\n");
if ((0 == strcmp(argv[1], "-w")) && (argc == 3))
{
len = strlen(argv[2]) + 1;
len = len < 1024 ? len : 1024;
ret = write(fd, argv[2], len);
printf("write driver : %d\n", ret);
} else {
len = read(fd, buf, 1024);
printf("read driver : %d\n", len);
buf[1023] = '\0';
printf("APP read : %s\n", buf);
}
close(fd);
return 0;
}
驱动程序属于模块写法:预先注册自己的的函数任务,以便服务于将来的某个请求,然后它的初始化函数就立即结束
因为驱动程序是调用的内核头文件,所以首先需要确认头文件有没有,下面第一条命令是确认有没有,没有的话,使用第二条进行下载。
apt-cache search linux-headers-$(uname -r)
sudo apt-get install linux-headers-$(uname -r)
代码见下图:
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>
static int major = 0;
static int ker_val = 123;
static struct class *hello_for_class;
static ssize_t hello_read(struct file *file, char __user *buf, size_t size, loff_t *offset)
{
printk("%s %s line %d\n",__FILE__,__FUNCTION__, __LINE__);
return 4;
}
static ssize_t hello_write(struct file *file, const char __user *buf, size_t size, loff_t *offset)
{
printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
return 4;
}
int __init hello_init(void)
{
printk("hello_linux_dri init\n");
return 0;
}
void __exit hello_exit(void)
{
printk("hello_linux_dri exit\n");
return;
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
上述就是驱动代码的一个基本框架
使用file_operations结构体来填充register_chrdev函数来注册驱动
static struct file_operations hello_linux_fops = {
.owner = THIS_MODULE,
.read = hello_read,
.write = hello_write,
};
int __init hello_init(void)
{
printk("hello_linux_dri init\n");
major = register_chrdev(0,"hello_linux_dri", &hello_linux_fops);
return 0;
}
使用unregister_chrdev函数来注销注册中的驱动信息
void __exit hello_exit(void)
{
printk("hello_linux_dri exit\n");
unregister_chrdev(major, "hello_linux_dri");
return;
}
使用class_create和device_create来进行生成,代码如下:
int __init hello_init(void)
{
printk("hello_linux_dri init\n");
major = register_chrdev(0,"hello_linux_dri", &hello_linux_fops);
hello_for_class = class_create(THIS_MODULE, "hello_class");
device_create(hello_for_class, NULL, MKDEV(major, 0), NULL, "hello_linux_dri");
return 0;
}
使用device_destroy和class_destroy进行撤销,代码如下:
void __exit hello_exit(void)
{
printk("hello_linux_dri exit\n");
device_destroy(hello_for_class, MKDEV(major, 0));
class_destroy(hello_for_class);
unregister_chrdev(major, "hello_linux_dri");
return;
}
效果如下:
完整代码见附件