4. 编写Android内置C可执行程序访问Linux内核驱动程序

本文是在上文3. 编写linux内核驱动程序(Android 10)的基础上进行的,虚拟机环境就是上文结束时的环境。本文将使用c可执行程序调用并测试上文写的驱动程序的read函数和write函数。

增加c可执行程序

在external目录下新建hello文件夹,在hello文件夹中新建hello.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define DEVICE_NAME "/dev/hello"
#define VAL_LENGTH 100
int main()
{
	int fd = -1;
	char val[VAL_LENGTH];
    char new_val[VAL_LENGTH];
	fd = open(DEVICE_NAME, O_RDWR);
	if(fd == -1) {
		printf("Failed to open device %s.\n", DEVICE_NAME);
		return -1;
	}
	
	printf("Read original value:\n");
	read(fd, val, VAL_LENGTH-1);
	printf("%s.\n\n", val);
	char val2[VAL_LENGTH] = "written_by_c";
	printf("Write value %s to %s.\n\n", val2, DEVICE_NAME);
    write(fd, val2, strlen(val2)+1);
	
	printf("Read the value again:\n");
    read(fd, new_val, VAL_LENGTH-1);
    printf("%s.\n\n", new_val);
	close(fd);
	return 0;
}

在hello文件夹中新建Android.mk文件

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE := hello
LOCAL_SRC_FILES := $(call all-subdir-c-files)
include $(BUILD_EXECUTABLE)

编译

编译hello模块

cd ~/Documents/aosp10
export TARGET_PREBUILT_KERNEL=/home/test/Documents/msm/arch/arm64/boot/Image.lz4-dtb
source build/envsetup.sh
lunch
aosp_walleye-userdebug
mmm ./external/hello

 可以看到生成的hello可执行程序

 重新打包system.img

time make snod -j16
time make -j16

重新刷入手机

sudo su
source build/envsetup.sh
lunch
aosp_walleye-userdebug
adb shell reboot bootloader
cd out/target/product/walleye/
fastboot flashall -w

 测试

adb shell
su
cd system/bin
./hello

本文涉及到的知识主要和Android架构中的linux内核层、系统运行库层相关

参考

在Ubuntu上为Android系统内置C可执行程序测试Linux内核驱动程序_老罗的Android之旅-CSDN博客

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值