01字符设备驱动框架
02编写Hello驱动程序
- 2.1写驱动程序的步骤
- 2.2 驱动程序代码
#include <linux/mm.h>
#include <linux/miscdevice.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mman.h>
#include <linux/random.h>
#include <linux/init.h>
#include <linux/raw.h>
#include <linux/tty.h>
#include <linux/capability.h>
#include <linux/ptrace.h>
#include <linux/device.h>
#include <linux/highmem.h>
#include <linux/backing-dev.h>
#include <linux/shmem_fs.h>
#include <linux/splice.h>
#include <linux/pfn.h>
#include <linux/export.h>
#include <linux/io.h>
#include <linux/uio.h>
#include <linux/module.h>
#include <linux/uaccess.h>
static int major;
static int hello_open (struct inode *node, struct file *filp)
{
printk("%s %s %d\n",__FILE__,__FUNCTION__,__LINE__);
return 0;
}
static ssize_t hello_read (struct file *filp, char __user *buf, size_t size, loff_t *offset)
{
printk("%s %s %d\n",__FILE__,__FUNCTION__,__LINE__);
return size;
}
static ssize_t hello_write (struct file *filp, const char __user *buf, size_t size, loff_t *offset)
{
printk("%s %s %d\n",__FILE__,__FUNCTION__,__LINE__);
return 0;
}
static int hello_release (struct inode *node ,struct file *filp)
{
printk("%s %s %d\n",__FILE__,__FUNCTION__,__LINE__);
return 0;
}
/* 1. create file_operations*/
static const struct file_operations hello_drv = {
.owner = THIS_MODULE,
.read = hello_read,
.write = hello_write,
.open = hello_open,
.release =hello_release,
};
/*2. register_chrdev */
/* 3.entry function */
static int __init hello_init(void)
{
major = register_chrdev(0, "100ask_hello", &hello_drv);
return 0;
}
/* 4.exit function */
static void __exit hello_exit(void)
{
unregister_chrdev(major, "100ask_hello");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
- 2.3 应用程序代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
/* write: /hello_test /dev/xxx 100ask
* read: /hello_test /dev/xxx
*/
int main(int argc ,char**argv)
{
int fd;
int len;
char buf[100];
if(argc<2)
{
printf("Usage\n");
printf("%s <dev> [string]\n",argv[0]);
return -1;
}
//open
fd = open(argv[1],O_RDWR);
if(fd < 0)
{
printf("can not open file %s\n",argv[0]);
return -1;
}
if(argc ==3)
{
//write
len = write(fd,argv[2],strlen(argv[2])+1);
printf("write ret = %d\n",len);
}
else
{
//read
len =read(fd,buf,100);
buf[99]='\0';
printf("read str:%s\n",buf);
}
//close
close(fd);
return 0;
}
Makefile文件
KERN_DIR = /home/book/100ask_imx6ull-sdk/Linux-4.9.88
all:
make -C $(KERN_DIR) M=`pwd` modules
$(CROSS_COMPILE)gcc -o hello_test hello_test.c
clean:
make -C $(KERN_DIR) M=`pwd` modules clean
rm -rf modules.order
rm -f hello_test
obj-m += hello_drv.o
2.4步骤
insmod hello_drv.ko
cat /proc/devices
mknod /dev/xyz c245 0(后边可以使用class_create自动创建节点)
./hello_test /dev/xyz 100ask
./hello_test /dev/xyz
- 2.5 运行结果