字元裝置模板

2021-09-21 15:09:17 字數 3263 閱讀 6438

源**:

#include #include 

#include

#include

#include

#include

#include

#include

#include

#include

//module_param(mem_major, int, s_irugo);

#define memdev_major 260 /*預設的mem的主裝置號*/

#define memdev_nr_devs 2 /*裝置數*/

#define memdev_size 4096

#define char_dev_name "memdev"

static

int mem_major = 0; //

memdev_major;

struct

class *pclass =null;

struct

cdev my_dev;

int mem_open(struct inode *inode, struct file *filp)

int mem_release(struct inode *inode, struct file *filp)

/*'k'為幻數,要按照linux核心的約定方法為驅動程式選擇ioctl編號,

應該首先看看include/asm/ioctl.h和documentation/ioctl-number.txt這兩個檔案.

對幻數的編號千萬不能重複定義,如ioctl-number.txt已經說明『k'的編號已經被占用的範圍為:

'k' 00-0f linux/spi/spidev.h conflict!

'k' 00-05 video/kyro.h conflict!

所以我們在這裡分別編號為0x1a和0x1b

*/#define cmd_magic 'k'

#define mem_cmd1 _io(cmd_magic, 0x1a)

#define mem_cmd2 _io(cmd_magic, 0x1b)

int temp_data = 0

;static

int mem_ioctl( struct file *file, unsigned int cmd, unsigned long

arg)

//printk(kern_notice"ioctl cmd%d done!\n",temp);

return0;

}static

const

struct file_operations mem_fops =;

static

int memdev_init(void

)

else

if (result < 0

)

return

result;

cdev_init(&my_dev, &mem_fops);

my_dev.owner =this_module;

my_dev.ops = &mem_fops;

cdev_add(&my_dev, mkdev(mem_major, 0

), memdev_nr_devs);

pclass =class_create(this_module, char_dev_name);

if(is_err(pclass))

device_create(pclass, null, devno, null, char_dev_name);

return

0;

failed:

cdev_del(&my_dev);

unregister_chrdev_region(devno,

1);

return

result;

}

static

void memdev_exit(void

)

module_author(

"derek yi

");

module_license(

"gpl

");

module_init(memdev_init);

module_exit(memdev_exit);

makefile:

ifneq ($(kernelrelease),)

obj-m:=memdev.o

else

kerneldir:=/lib/modules/$(shell uname -r)/build

pwd:=$(shell pwd)

default

: $(make) -c $(kerneldir) m=$(pwd) modules

clean:

rm -rf *.o *.mod.c *.mod.o *.ko

endif

測試**:

#include #include 

#include

#include

#include

#include

#include

#include

#define cmd_magic 'k'

#define mem_cmd1 _io(cmd_magic, 0x1a) //

write

#define mem_cmd2 _io(cmd_magic, 0x1b) //

read

intmain()

ret = ioctl(fd, mem_cmd2, &rdata);

printf(

"ioctl: ret=%d rdata=%d\n

", ret, rdata);

wdata = 42

; ret = ioctl(fd, mem_cmd1, &wdata);

ret = ioctl(fd, mem_cmd2, &rdata);

printf(

"ioctl: ret=%d rdata=%d\n

", ret, rdata);

close(fd);

return0;

}

linux驅動字元裝置模板

基於linux 4.4版本,板載6410 include 包含file operation結構體 include 包含module init module exit include 包含license的巨集 include 包含copy to user之類 include include 包含ior...

linux字元裝置驅動開發模板及Makefile

include include include include include 字元裝置驅動模板開始 define char dev device name char dev 是應當連線到這個編號範圍的裝置的名字,出現在 proc devices和sysfs中 define char dev nod...

Linux 驅動學習筆記 字元裝置驅動模板 一

驅動入口函式 static int init init void 驅動出口函式 static void exit exit void 將上面兩個函式指定為驅動的入口和出口函式 module init init module exit exit module license gpl 新增協議 modu...