第七期 基于模拟器的Helloworld 可执行程序 《手机就是开发板》

https://blog.csdn.net/aggresss/article/details/53561241

这一期我们来写一个小程序运行在android 的shell里面,和普通的linux shell一个原理,用这个可执行文件来验证上一期写的驱动程序,也就是操作 /dev/hello 设备文件。
下面提到的代码可以到https://github.com/aggresss/PHDemo 的Code 目录下的 hello_Execute 文件中下载,也可以访问这个链接直接查看:
https://github.com/aggresss/PHDemo/tree/master/Code/hello_Execute
进入到AOSP根目录,进入external目录,mkdir hello,在hello目录下新建hello.c

#include <stdio.h>  
#include <stdlib.h>  
#include <fcntl.h>  
#define DEVICE_NAME "/dev/hello"  
int main(int argc, char** argv)  
{  
    int fd = -1;  
    int val = 0;  
    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, sizeof(val));  
    printf("%d.\n\n", val);  
    val = 5;  
    printf("Write value %d to %s.\n\n", val, DEVICE_NAME);  
        write(fd, &val, sizeof(val));  
      
    printf("Read the value again:\n");  
        read(fd, &val, sizeof(val));  
        printf("%d.\n\n", val);  
    close(fd);  
    return 0;  
}  


这个程序的执行过程是 打开/dev/hello 文件,读出 /dev/hello 中的值,然后写入5 到/dev/hello中,最后再次读出/dev/hello中的值。
在 ./external/hello目录下新建一个Android.mk文件,它的作用相当于AOSP系统中的Makefile。在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)


回到AOSP根目录执行
mmm ./external/hello
编译成功后就可以在out/target/product/gerneric/system/bin目录下看到ELF格式的hello文件了。
执行 make snod 重新生成镜像。

emulator -kernel ./kernel3.4/arch/arm/boot/zImage &
adb shell
cd system/bin
./hello

这个小实验非常简单,但是可以从感性上让我们体会到原来android系统就是运行在linux系统上的一个架构,有些时候就是这样,不动手实践一下总是不能真正领悟,Google通过增加Android framework 架构让 android 的APP 生态系统使用JAVA来构建。不过,这个架构的复杂程度可能不会比linux内核简单多少。
 

猜你喜欢

转载自blog.csdn.net/wxh0000mm/article/details/86300776
今日推荐