編輯:關於 Android 程式設計
一直想找機會親手試一次「用 Android 應用訪問 Linux 內核驅動」,卻總被各種事情耽擱。最近終於騰出時間,下定決心重新試一試。整個嘗試自然要從一個 Linux 內核驅動開始。
我的目標是寫一個簡單的測試驅動:寫入一段字串,再把它讀出來。驅動會創建 /dev/hello 設備節點和 /sys/class/hello/hello/val 設備節點(暫未實現 proc 節點)。前者主要供上層應用調用,後者則方便我們快速測試。
以下代碼已在 Android 6.0 的 Linux kernel 上驗證通過,並附有相應注釋:
#include#include #include #include #include #include #include #include #include #include #include #include #include #include #include "hello.h" /* 定義主設備和從設備號變量 */ static int hello_major = 0; static int hello_minor = 0; /* 設備類別和設備變量 */ static struct class* hello_class = NULL; static struct hello_test_dev* hello_dev = NULL; /* 傳統的設備文件操作方法 */ static int hello_open(struct inode* inode, struct file* filp); static int hello_release(struct inode* inode, struct file* filp); static ssize_t hello_read(struct file* filp, char __user *buf, size_t count, loff_t* f_pos); static ssize_t hello_write(struct file* filp, const char __user *buf, size_t count, loff_t* f_pos); /* 設備文件操作方法表 */ static struct file_operations hello_fops = { .owner = THIS_MODULE, .open = hello_open, .release = hello_release, .read = hello_read, .write = hello_write, }; /* 訪問設置屬性方法 */ static ssize_t hello_val_show(struct device* dev, struct device_attribute* attr, char* buf); static ssize_t hello_val_store(struct device* dev, struct device_attribute* attr, const char* buf, size_t count); /* 定義設備屬性 */ static DEVICE_ATTR(val, S_IRUGO | S_IWUSR, hello_val_show, hello_val_store); /* 打開設備方法 */ static int hello_open(struct inode* inode, struct file* filp) { struct hello_test_dev* dev; dev = container_of(inode->i_cdev, struct hello_test_dev, dev); filp->private_data = dev; return 0; } /* 設備文件釋放時調用,空實現 */ static int hello_release(struct inode* inode, struct file* filp) { return 0; } /* 讀內存 */ static ssize_t hello_read(struct file* filp, char __user *buf, size_t count, loff_t* f_pos) { ssize_t err = 0; struct hello_test_dev* dev = filp->private_data; if(down_interruptible(&(dev->sem))) { return -ERESTARTSYS; } if(count < sizeof(dev->val)) { goto out; } if(copy_to_user(buf, dev->val, sizeof(dev->val))) { err = -EFAULT; goto out; } err = sizeof(dev->val); out: up(&(dev->sem)); return err; } /* 寫字符串 */ static ssize_t hello_write(struct file* filp, const char __user *buf, size_t count, loff_t* f_pos) { struct hello_test_dev* dev = filp->private_data; ssize_t err = 0; if(down_interruptible(&(dev->sem))) { return -ERESTARTSYS; } if(count != sizeof(dev->val)) { goto out; } if(copy_from_user(dev->val, buf, count)) { err = -EFAULT; goto out; } err = sizeof(dev->val); out: up(&(dev->sem)); return err; } /* 寫字符串到內存 */ static ssize_t __hello_set_val(struct hello_test_dev* dev, const char* buf, size_t count) { if(down_interruptible(&(dev->sem))) { return -ERESTARTSYS; } printk(KERN_ALERT"__hello_set_val.buf: %s count:%d\n",buf,count); strncpy(dev->val,buf, count); up(&(dev->sem)); return count; } /* 讀取設備屬性 val */ static ssize_t hello_val_show(struct device* dev, struct device_attribute* attr, char* buf) { struct hello_test_dev* hdev = (struct hello_test_dev*)dev_get_drvdata(dev); return 0; } /* 寫設備屬性 val */ static ssize_t hello_val_store(struct device* dev, struct device_attribute* attr, const char* buf, size_t count) { struct hello_test_dev* hdev = (struct hello_test_dev*)dev_get_drvdata(dev); return __hello_set_val(hdev, buf, count); } /* 初始化設備 */ static int __hello_setup_dev(struct hello_test_dev* dev) { int err; dev_t devno = MKDEV(hello_major, hello_minor); memset(dev, 0, sizeof(struct hello_test_dev)); cdev_init(&(dev->dev), &hello_fops); dev->dev.owner = THIS_MODULE; dev->dev.ops = &hello_fops; err = cdev_add(&(dev->dev),devno, 1); if(err) { return err; } init_MUTEX(&(dev->sem)); dev->val = kmalloc(10,GFP_KERNEL); strncpy(dev->val,"hello",sizeof("hello")); return 0; } /* 模塊加載方法 */ static int __init hello_init(void){ int err = -1; dev_t dev = 0; struct device* temp = NULL; err = alloc_chrdev_region(&dev, 0, 1, HELLO_DEVICE_NODE_NAME); if(err < 0) { goto fail; } hello_major = MAJOR(dev); hello_minor = MINOR(dev); hello_dev = kmalloc(sizeof(struct hello_test_dev), GFP_KERNEL); if(!hello_dev) { err = -ENOMEM; goto unregister; } err = __hello_setup_dev(hello_dev); if(err) { goto cleanup; } hello_class = class_create(THIS_MODULE, HELLO_DEVICE_CLASS_NAME); if(IS_ERR(hello_class)) { err = PTR_ERR(hello_class); goto destroy_cdev; } temp = device_create(hello_class, NULL, dev, "%s", HELLO_DEVICE_FILE_NAME); if(IS_ERR(temp)) { err = PTR_ERR(temp); goto destroy_class; } err = device_create_file(temp, &dev_attr_val); if(err < 0) { goto destroy_device; } dev_set_drvdata(temp, hello_dev); return 0; destroy_device: device_destroy(hello_class, dev); destroy_class: class_destroy(hello_class); destroy_cdev: cdev_del(&(hello_dev->dev)); cleanup: kfree(hello_dev); unregister: unregister_chrdev_region(MKDEV(hello_major, hello_minor), 1); fail: return err; } /* 模塊卸載方法 */ static void __exit hello_exit(void) { dev_t devno = MKDEV(hello_major, hello_minor); if(hello_class) { device_destroy(hello_class, MKDEV(hello_major, hello_minor)); class_destroy(hello_class); } if(hello_dev) { cdev_del(&(hello_dev->dev)); kfree(hello_dev); } unregister_chrdev_region(devno, 1); } MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Test Driver"); module_init(hello_init); module_exit(hello_exit);
#ifndef _HELLO_TEST_H_ #define _HELLO_ANDROID_H_ #include#include #define HELLO_DEVICE_NODE_NAME "hello" #define HELLO_DEVICE_FILE_NAME "hello" #define HELLO_DEVICE_CLASS_NAME "hello" struct hello_test_dev { char * val; struct semaphore sem; struct cdev dev; }; #endif
在 Linux 源碼目錄的 drivers 下新建 hello 目錄,放入 hello.c 和 hello.h,並新增 Makefile 與 Kconfig 文件。
obj-$(CONFIG_HELLO) += hello.o
config HELLO tristate "Test Driver" default n help This is the test driver.
obj-$(CONFIG_HELLO) += hello/
source "drivers/hello/Kconfig"
執行 make menuconfig 進行配置,可以看到我們新增的 Test Driver 選項:

將它選為以模塊形式編譯,更有利於測試,這樣就不必重新燒寫整個 kernel。Android 的 Linux kernel 通常打包進 boot.img,若想將模塊編進內核並重寫燒寫,建議把 kernel 放到 out/target/product/xxx/ 目錄下,再使用 make bootimage-nodeps 快速生成 boot.img,具體位置需參照 Android 編譯系統的相關配置。
執行 make -j16(-j16 表示請求使用 16 個 CPU 編譯),幾分鐘即可完成。編譯後的 hello 目錄會生成 hello.ko 文件:

建議直接用 adb push hello.ko /data,也可用 U 盤拷貝,總之把它放到 Android 設備上。
cd /data insmod hello.ko
此時 /dev/hello 與 /sys/class/hello/hello/val 節點便會出現。
寫入命令 echo haha > val,內核會打印類似:
[ 9641.053505] hello_val_store.buf: haha [ 9641.060167] __hello_set_val.buf: haha [ 9641.073088] __hello_set_val.dev->val: haha
可見數據已寫入。再用 cat val 讀取,會打印出 haha,說明寫入成功。
在 Android 源碼的 packages 目錄下新建 hellotest 目錄,並在其中創建 hellotest.c 和 Android.mk。
這個程序負責打開 /dev/hello,進行讀寫並打印結果:
#include#include #include #define HELLO_DEVICE "/dev/hello" int main(int argc, char** argv) { int fd = -1; char * str = malloc(10); fd = open(HELLO_DEVICE, O_RDWR); if(fd == -1) { printf("Failed to open device %s.\n", HELLO_DEVICE); return -1; } printf("Read original value:\n"); read(fd, str, 10); printf("read data: %s\n", str); strncpy(str,"nihao",sizeof("nihao")); printf("write nihao\n"); write(fd, str, sizeof(str)); printf("Read the value again:\n"); read(fd, str, 10); printf("read data: %s\n", str); close(fd); return 0; }
在 Android 下用 Android.mk 編譯可執行程序很方便:
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE_TAGS := optional LOCAL_MODULE := hellotest LOCAL_SRC_FILES := $(call all-subdir-c-files) include $(BUILD_EXECUTABLE)
執行 mm 命令即可。編譯後的文件位於 out/target/product/xxx/obj/EXECUTABLES/hellotest_intermediates/ 目錄下:

用 adb push hellotest /data 推送到設備,再 chmod +x hellotest 添加執行權限,最後執行 ./hellotest,輸出如下:
Read original value: read data: hello write nihao Read the value again: read data: nihao
可見讀寫均正常,測試成功。
Android SQLite 基本操作:建立資料庫與增刪改查
SQLite 是 Android 內建的輕量級關聯式資料庫,適合儲存結構化資料。即使不熟 SQL,也可透過 SQLiteOpenHelper 與 SQLiteDataba
Android 自定義 View 知識梳理:從屬性到繪製
雖然 Android 提供了豐富的內建控制項,但在面對特殊介面、品牌風格或互動效果時,自定義 View 仍然是開發者必備的能力。掌握自定義 View 的建構流程、屬性解析
Android AutoCompleteTextView 搭配 TextWatcher 動態提示
AutoCompleteTextView 是什麼 AutoCompleteTextView 是可動態提示輸入內容的輸入框。當使用者輸入部分文字時,它會顯示候選清單,例如輸
解決 Android Studio 代理隧道 400 Bad Request 的 Gradle 設定方法
問題描述 更新 Android Studio 後,導入新專案時出現 Error: Unable to tunnel through proxy. Proxy return