本文基于android 28 源码
com.android.internal.os.ZygoteInit.java
com.android.internal.os.ZygoteServer.java
com.android.internal.os.ZygoteConnection.java
android.os.ZygoteProcess.java
在ZygoteInit.java源码的main函数中创建 zygoteServer对象并 并注册服务Socket
ZygoteServer zygoteServer = new ZygoteServer(); zygoteServer.registerServerSocketFromEnv(socketName);
然后调用 forkSystemServer 创建SystemServer
try{
caller = zygoteServer.runSelectLoop(abiList);//等待AMS客户端 连接,并返回 Runnable
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with exception", ex);
throw ex;
} finally {
zygoteServer.closeServerSocket();
}
// We're in the child process and have exited the select loop. Proceed to execute the
// command.
if (caller != null) {
caller.run();
}

/* * Pass the remaining arguments to SystemServer. */ return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);

接着调用静态方法findStaticMain,传入全路径类名,参数和 类加载器

最终实例化MethodAndArgsCaller 类 并反射调用SystemServer 的 main 函数,如果不为空则调用其 run函数
接着往下看 zygoteServer.runSelectLoop(abiList) 中 部分源码,
args = readArgumentList(); 读取客户端 socket 参数
只有一处返回Runnable便是 ZygoteConnection的processOneCommand 函数

接着执行 Zygote.forkAndSpecialize 函数
返回如果这是child,pid=0
如果这是parent,pid=-1

接着执行 handleChildProc 函数 启动 时parsedArgs.invokeWith 为空( 即没有添加--invoke-with) 执行else

这两个分支最终都是 调用 findStaticMain 函数 创建 MethodAndArgsCaller 对象 返回 Runnable
最终在 ZygoteInit中调用 执行run函数
if (caller != null) {
caller.run();
}
至此成功调用 到 ActivityThread 的main 函数

本文深入剖析了Android系统中Zygote进程的工作原理,从ZygoteInit.java的main函数开始,详细介绍了如何创建ZygoteServer对象并注册服务Socket,再到forkSystemServer创建SystemServer的过程。通过分析ZygoteServer的runSelectLoop函数,揭示了如何处理客户端连接请求及参数读取,以及Zygote.forkAndSpecialize函数的执行流程。最终,文章展示了如何通过findStaticMain函数调用ActivityThread的main函数。
6754

被折叠的 条评论
为什么被折叠?



