1. 程式人生 > >Linux 添加設備驅動程序

Linux 添加設備驅動程序

access char int 驅動 all sizeof inode gif ide

  1.創建驅動文件my_drive.c

技術分享圖片
#include "linux/kernel.h"
#include "linux/module.h"
#include "linux/fs.h"
#include "linux/init.h"
#include "linux/types.h"
#include "linux/errno.h"
#include "linux/uaccess.h"
#include "linux/kdev_t.h"
 
#define MAX_SIZE 1024
 
int my_open(struct inode *inode, struct file *file);
int my_release(struct inode *inode, struct file *file); ssize_t my_read(struct file *file, char __user *user, size_t t, loff_t *f); ssize_t my_write(struct file *file, const char __user *user, size_t t, loff_t *f); char message[MAX_SIZE] = "my drive start to work"; //打開設備時會顯示的消息 int device_num;//
設備號 char* devName = "my_drive";//設備名 struct file_operations pStruct = { open:my_open, release:my_release, read:my_read, write:my_write, }; /* 註冊 */ int init_module() { int ret; ret = register_chrdev(0, devName, &pStruct); if (ret < 0) { printk(
"failed to register my drive.\n"); return -1; } else { printk("my drive has been registered!\n"); printk("id: %d\n", ret); device_num = ret; return 0; } } //註銷 void cleanup_module() { unregister_chrdev(device_num, devName); printk("unregister successful.\n"); } //打開 int my_open(struct inode *inode, struct file *file) { printk("open my_drive OK!\n"); try_module_get(THIS_MODULE); return 0; } //關閉 int my_release(struct inode *inode, struct file *file) { printk("Device released!\n"); module_put(THIS_MODULE); return 0; } //讀設備裏的信息 ssize_t my_read(struct file *file, char __user *user, size_t t, loff_t *f) { if(copy_to_user(user,message,sizeof(message))) { return -2; } return sizeof(message); } //向設備裏寫信息 ssize_t my_write(struct file *file, const char __user *user, size_t t, loff_t *f) { if(copy_from_user(message,user,sizeof(message))) { return -3; } return sizeof(message); }
my_drive.c

  2.同目錄下創建Makefile

技術分享圖片
obj-m := my_drive.o    #這裏是上面所創建的c文件名.o
    PWD := $(shell pwd)
    KERNELDIR := /usr/src/linux-4.14    #你要安裝mod的內核版本 
all:
    make -C $(KERNELDIR) M=$(PWD) modules
 
 
.PHONY: clean
clean:
    rm -rf *.o *~ core *.ko *.mod.c modules.order Module.symvers
Makefile

  3.使用make生成驅動程序

  4.插入內核模塊insmod chardev.ko

  5.查看內核輸出日誌dmesg,獲取設備號

  6.根據輸出的設備號,創建設備mknod /dev/my_drive c 245 0 (245為設備號)

  7.編寫測試程序

技術分享圖片test.c

  8.效果 

  技術分享圖片

  9.卸載設備和模塊

  rm /dev/my_drive

  rmmod my_drive

Linux 添加設備驅動程序