linux DEVICE ATTR建立裝置節點程式

2021-08-27 08:31:14 字數 1787 閱讀 6311

一、簡述:

通過device_attr建立裝置節點,可以完成一些簡單的驅動的測試工作,可以向節點做echo cat相關的操作。

二、**如下:

(1)驅動**:

#include #include #include #include #include //執行cat會呼叫到此函式

static ssize_t hello_test_show(struct device *dev, struct device_attribute *attr, char *buf)

ptr[size] = 'x';

kfree(ptr);

return 0;

}//執行echo 1 > hello_test會執行到此函式

static ssize_t hello_test_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)

static device_attr(hello_test, 0664, hello_test_show, hello_test_store);

//probe初始化函式

static int hello_test_probe(struct platform_device *pdev)

static const struct of_device_id hello_of_match = ,

,};//platform_driver 的結構

static struct platform_driver hello_test_driver =

};static int __init hello_init(void)

static void __exit hello_exit(void)

module_init(hello_init);

module_exit(hello_exit);

/* module information */

module_author("hello_test");

module_description("hello driver");

module_license("gpl v2");

(2)makefile  kconfig dts:

//makefile

obj-$(config_hello_test) +=hello_test/

//kconfig

config hello_test

bool "hello_test for transsion solution"

default n

//dts

hello_test: hello_test ;

三、測試:

(1)adb 到裝置中可以看到如下節點:

/sys/bus/platform/drivers/hello_test/odm:hello_test/

driver driver_override   hello_test   modalias of_node power subsystem uevent

(2)執行如下的命令會呼叫到hello_test_show或hello_test_store函式:

cat hello_test

echo 1 > hello_test

(3)執行如下命令可以看到對應的kernel log中有輸出列印:

while  true; do cat /proc/kmsg | grep -nr hello ; done;

建立裝置節點

書中所使用的是mknod命令手動建立節點,事實上有一組函式支援自動建立裝置節點。核心中定義了struct class結構體,乙個struct class結構體變數對應乙個類,核心提供了class create巨集來建立乙個類。呼叫class create會在 sys class目錄下生成乙個目錄,接...

linux自動建立裝置節點

在有2.6系列版本中支援udev管理裝置檔案可以方便的建立裝置節點,不必使用mknod來建立 主要用到的四個方法在linux device.h定義 建立類和釋放類的函式 建立成後將建立 sys class name資料夾 extern struct class class create struct...

Linux dev 自動建立裝置節點

udev的支援主要作用是 在驅動初始化的 裡呼叫class create 為該裝置建立乙個class,再為每個裝置呼叫device create 核心中定義的struct class結構體,顧名思義,乙個struct class結構體型別變數對應乙個類,核心同時提供了class create 函式,...