上一篇讲了Zygote是如何收到启动Application的启动消息,并一步步进入Fork(),下面来分析zygote fork启动application后,application进程后续处理操作,是如何真正的启动的。
- ZygoteInit.main():
- -->...
- caller = ZygoteServer.runSelectLoop();
- -->while(true) //死循环
- -->Zygoteconnection connection = peers.get();
- Runnable command = connection.processOneCommand();//进行进程的处理,创建新进程
- -->args = Zygote.readArgumentList(mSocketReader);//获取socket命令参数
- ZygoteArguments parsedArgs = new ZygoteArguments();
- ...各种参数解析中...
- pid = zygote.forkAndSpecialize();//Fork子进程,得到一个新的pid.
- -->pid = nativeForkAndSpecialize(); //调用native层接口去fork
- if(pid == 0){ //子进程
-
- }
- return pid;
- if(pid == 0) //子进程:Application进程
- {
- //关闭Zygote服务Socket:因为fork时复制出来的socket,对Application进程来说,它没有用。
- zygoteServer.closeServerSocket();
- //application进程可以正常运行了。
- return handleProcessChild();
- -->ZygoteConnection.java:
- ZygoteInit.zygoteInit(parseArgs.xxx); //app进程的启动
- -->ZygoteInit.java:
- RuntimeInit.commonInit(); //初始化运行环境
- ZygoteInit.nativeZygoteInit();//启动Binder, 并在androidRuntime.cpp中注册
- -->com_android_internal_os_ZygoetInit_ativeZygoteInit():
- -->gCurRuntime->onZygoteInit(); //通过JNI进入Native
- -->//进入app_main.cpp.onZygoteInit();
- //下面ProcessState对应Application这个进程实例,里面会初始化Binder
- -->sp<ProcessState> proc = ProcessState::self();
- -->在C++构造函数初始化列表中:mDriverFD(open_driver(driver))
- //这里总结下,Application被Zygote Fork出来之后,进入到Native层处理的目的是为了构建Binder.
- //因为后续的跨进程通信,都需要借助Binder.后续将此Binder发给AMS,AMS拿到App的IBinder,才能
- //够通过AMS的服务来与APP通信。
- proc->startThreadPool(); //启动Binder线程池
-
- //里面通过反射创建程序入口函数的Method对象,并返回Runnable对象
- return RuntimeInit.applicationInit();
- //类名字,类参数,加载器
- -->return findStaticMain(args.startClass, args.startArgs,classLoader);
- //通过反射拿到对应类的main方法的Method对象:找到的就是ActivityThread.java.main();
- -->m = cl.getMethod("main",new class[]{string[].class});
- return 近回一个Runnable 对象。
- }else{ //zygote 进程
-
- }
- ...
- //Runnable对象返回到这里,对应上面代码中的Runnable command = connection.processOneCommand();后面
- //继续接着返回,最后返回到上面代码的caller = ZygoteServer.runSelectLoop();
- if(caller != null)
- caller.run(); //执行返回的Runnable对象,进入子进程。
- -->RuntimeInit.java.MethodAndArgsCaller->run();
- -->mMethod.invoke();//java反射原理。(执行的是ActivityThread.java的main())
分析时需要注意的是,底层调用linux fork()接口之后,会有两个返回值,如果pid =0,表示返回的是子进程,如果pid >0,返回的是父进程(即zygote的程序运行路线),父进程(zygote进程)可以得知子进程的pid号。
补充一个要点:ApplicationThread是什么?它其实是一个IApplicationThread.Stub对象,通过IBinder对象进行跨进程通信访问时,ApplicationThread本质就是Binder线程池中的一个线程(关联到上面代码中的proc->startThreadPool() )