本文主要是介绍Android源码(10) --- Binder(4) ServiceManager 启动,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
纵观Binder通讯过程,无不在跟ServiceManager打交道,了解ServiceManager 交互流程就显得很有必要了。ServiceManager分为启动和、获取、添加、注册服务。首先从启动过程来了解,ServiceManager如何成为Binder守护进程。
源码路径
android/system/core/rootdir/init.rc
android/frameworks/native/cmds/servicemanager/|-- service_manager.c|-- binder.c
Binder内核
1 启动ServiceManager
- 1.Android在init进程启动以后,通过脚本init.rc,启动ServiceManager:
|– init.rc
service servicemanager /system/bin/servicemanagerclass coreuser systemgroup systemcriticalonrestart restart healthdonrestart restart zygoteonrestart restart mediaonrestart restart surfaceflingeronrestart restart drm
对应执行程序/system/bin/servicemanager,源码service_manager.c。下一步追踪一下service_manager.c的main()入口程序。
2.1 main
|– service_manager.c
int main(int argc, char **argv)
{struct binder_state *bs;// 打开Binder驱动..并申请128字节内存bs = binder_open(128*1024);if (!bs) {ALOGE("failed to open binder driver\n");return -1;}// 变成 Context Managerif (binder_become_context_manager(bs)) {ALOGE("cannot become context manager (%s)\n", strerror(errno));return -1;}// 判断 selinux 权限能否使用selinux_enabled = is_selinux_enabled();sehandle = selinux_android_service_context_handle();selinux_status_open(true);if (selinux_enabled > 0) {if (sehandle == NULL) {// 获取sehandle 权限失败ALOGE("SELinux: Failed to acquire sehandle. Aborting.\n");abort();}if (getcon(&service_manager_context) != 0) {// 获取service_manager 上下文失败ALOGE("SELinux: Failed to acquire service_manager context. Aborting.\n");abort();}}union selinux_callback cb;cb.func_audit = audit_callback;selinux_set_callback(SELINUX_CB_AUDIT, cb);cb.func_log = selinux_log_callback;selinux_set_callback(SELINUX_CB_LOG, cb);// 进入 binder 循环binder_loop(bs, svcmgr_handler);return 0;
}
- mian 入口函数一共处理了三件事:
- 1.打开Binder驱动并申请内存
- 2.告诉Binder驱动成为Binder的上下文管理者(ServiceManager成为守护进程)
- 3.开启循环,处理IPC请求(等待Client请求)
2.2 binder_open
在ServiceManaer 的main入口第一步看到打开Binder驱动,调用了binder_open。binder_open又做了哪些具体的工作呢?
|– binder.c
struct binder_state *binder_open(size_t mapsize)
{struct binder_state *bs; // 初始化状态参数struct binder_version vers;bs = malloc(sizeof(*bs));if (!bs) {errno = ENOMEM;return NULL;}//打开 Binder 设备驱动bs->fd = open("/dev/binder", O_RDWR);if (bs->fd < 0) {fprintf(stderr,"binder: cannot open device (%s)\n",strerror(errno));goto fail_open; //打开失败}//系统调用 ioctl获取binder版本信息if ((ioctl(bs->
这篇关于Android源码(10) --- Binder(4) ServiceManager 启动的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!