Linux驅動開發之字元裝置讀操作

2021-08-21 00:18:07 字數 2381 閱讀 9188

1、驅動源**

#include

#include

#include

#include

#include

#include

static int hello_major = 248; // 主裝置號

static int hello_minor = 0; // 次裝置號

static int number_of_devices = 1; // 字元裝置個數

char data[50] = "i come from liux kernel!";

struct cdev cdev; // 靜態定義字元裝置

dev_t dev = 0; // 裝置號

static int hello_open(struct inode *inode, struct file *file)

static int hello_release(struct inode *inode, struct file *file)

ssize_t 

hello_read (struct file *filp, char *buff, size_t count, loff_t *offp)

ssize_t 

hello_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos)

else

return ret;

}struct file_operations hello_fops = ;

static void char_reg_setup_cdev (void)

static int __init hello_init(void)

char_reg_setup_cdev ();

printk (kern_info "write driver registered\n");

return 0;

}static void __exit hello_exit (void)

module_init (hello_init);

module_exit (hello_exit);

module_license("gpl");

module_version("v1.0");

module_author("[email protected]");

module_description("char driver module");

module_alias("char driver module");

2、makefile

ifeq ($(kernelrelease),)

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

pwd := $(shell pwd)

all:                               

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

clean:                                             

$(make) -c $(kerneldir) m=$(pwd) clean

else

obj-m := read_dev.o

endif

3、應用程式

#include

#include

#include

#include

#include

#include

int main (void) 

printf("/dev/hello opened, fd=%d\n",fd);

printf("write returns %d\n", write(fd,buff,sizeof(buff) - 1));

memset(buff, 0, 50);

printf ("read returns %d\n", read(fd, buff, sizeof(buff) - 1));

buff[49] = '0';

printf("buff = %s\n", buff);

close(fd);

printf("/dev/hello closed\n");

return 0;

4、驗證

1)sudo insmod read_dev.ko

2)手動建立裝置檔案

sudo mknod /dev/hello c 248 0

chmod 0666 /dev/hello

3)編譯應用程式

gcc test.c -o test

執行應用程式 ./test

4)檢視核心訊息

dmesg

linux核心字元裝置驅動之讀操作

char rbuf 1024 分配緩衝區,儲存讀取的資料 ret read fd,rbuf,1024 讀裝置,將從裝置讀取的資料儲存在rbuf緩衝區中,要讀1024位元組 ret儲存實際讀取的位元組數 struct file operations read介面作用 用於讀取裝置,並且將讀取的資料上報...

驅動 linux裝置驅動 字元裝置驅動開發

preface 前面對linux裝置驅動的相應知識點進行了總結,現在進入實踐階段!linux 裝置驅動入門篇 linux 裝置驅動掃盲篇 fedora下的字元裝置驅動開發 開發乙個基本的字元裝置驅動 在linux核心驅動中,字元裝置是最基本的裝置驅動。字元裝置包括了裝置最基本的操作,如開啟裝置 關閉...

Linux驅動開發之字元裝置驅動例項

1 驅動標頭檔案mem dev.h ifndef memdev h define memdev h ifndef memdev major define memdev major 238 預設的mem的主裝置號 endif ifndef memdev nr devs define memdev nr...