定義乙個file_operations結構體型別的變數
並填充owner函式、open函式、write函式
static int drvledopen(struct inode *inode, struct file *file)
static ssize_t drvledwrite(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
static struct file_operations drvfileoperations = ;
註冊/解除安裝驅動程式
static struct class *drvledclass;
static struct class_device *drvledclassdev;
...int major;
static int drvinit(void)
static void drvexit(void)
module_init(drvinit);
module_exit(drvexit);
module_license("gpl");
函式講解
register_chrdev() //註冊字元裝置驅動
函式原型:
int register_chrdev(unsigned int major, const char *name, const struct file_operations *fops)
引數:major:主裝置號,如果major == 0, 函式將自動分配主裝置號。如果major != 0,函式使用指定的主裝置號
name:裝置名稱
fops:(無需過多解釋)
返回值:
int:如果major == 0,裝置將返回乙個自動分配的主裝置號。
unregister_chrdev() //解除安裝字元裝置驅動
函式原型:
vint unregister_chrdev(unsigned int major, const char *name)
引數:major:主裝置號
name:裝置名稱
**********==== 自動建立裝置節點 start **********===
class_create() //建立乙個類
函式原型:
struct class *class_create(struct module *owner, const char *name)
引數:owner:與drvfileoperations結構體變數中的owner相同
name:裝置名稱
返回:類
class_device_create() //根據剛才的類資訊,建立乙個裝置節點
函式原型:
struct class_device *class_device_create(struct class *cls, struct class_device *parent, dev_t devt, struct device *device, const char *fmt, …)
引數:cls:指定所要建立的裝置節點所從屬的類
parent:這個裝置的父裝置,如果沒有就指定為null
devt:字元裝置的裝置號,通常使用mkdev(major, 0),
device:類下的裝置,如果沒有就指定為null
fmt:字元裝置節點的名稱
返回:裝置類
********** 自動建立裝置節點 end ***************==
**********=== 解除安裝 自動建立裝置節點 start**********
class_device_unregister() //解除安裝裝置節點
函式原型:
void class_device_unregister(struct class_device *class_dev)
引數:class_dev:裝置類
class_destroy() //解除安裝類
函式原型:
void class_destroy(struct class *cls)
引數:cls:類
*************** 解除安裝 自動建立裝置節點 start***************
當使用insmod *****.ko命令裝載驅動時,系統會自動呼叫module_init()函式
當使用rmmod *****.ko命令解除安裝驅動時,系統會自動呼叫module_exit()函式
應用程式呼叫:
如果在應用程式中使用open()和write()函式,驅動中的open()和write()函式將會被呼叫
fd = open("/dev/devdrvled", o_rdwr);
write(fd, &val, 4);
open()
函式原型:
static int open(struct inode *inode, struct file *file)
引數:inode:裝置節點
file:檔案開啟方式
返回:int:開啟失敗,返回-1。開啟成功返回裝置件控制代碼
write()
函式原型:
int write(ihandle instance, void *buf, int buflen)
引數:instance:將寫入的裝置的控制代碼
buf:寫入的資料變數,不限資料型別
buflen:寫入的資料長度
新增標頭檔案
#include //this_module; module_license();
#include //file_operations; register_chrdev(); unregister_chrdev();mkdev();
#include //class_create(); class_device_create(); class_device_unregister(); class_destroy();包含"linux/module.h"
編寫乙個小的測試程式 驅動 linux裝置驅動 字元裝置驅動開發
preface 前面對linux裝置驅動的相應知識點進行了總結,現在進入實踐階段!linux 裝置驅動入門篇 linux 裝置驅動掃盲篇 fedora下的字元裝置驅動開發 開發乙個基本的字元裝置驅動 在linux核心驅動中,字元裝置是最基本的裝置驅動。字元裝置包括了裝置最基本的操作,如開啟裝置 關閉...
Linux裝置驅動之《字元裝置驅動》
linux裝置中最大的特點就是裝置操作猶如檔案操作一般,在應用層看來,硬體裝置只是乙個裝置檔案。應用程式可以像操作檔案一樣對硬體裝置進行操作,如open close read write 等。下面是乙個字元裝置驅動程式的簡單實現test.c 模組分析 1.初始化裝置驅動的結構體 struct fil...
Linux裝置驅動之字元裝置驅動
一 linux裝置的分類 linux系統將裝置分成三種基本型別,每個模組通常實現為其中某一類 字元模組 塊模組或網路模組。這三種型別有 字元裝置 字元裝置是個能夠像位元組流 類似檔案 一樣被訪問的裝置,由字元裝置驅動程式來實現這種特性。字元裝置可以通過檔案系統節點來訪問,比如 dev tty1等。這...