本文基于 Android 9.0 , 代碼倉庫地址 : android_9.0.0_r45
文中原始碼鏈接:
Zygote.java
ZygoteInit.java
ZygoteServer.java
ZygoteConnection.java
RuntimeInit.java
仔細看看下面這張 Android 體系圖,找一下 Zygote 在什么地方,

上圖來自 Gityuan 博客 ,
縱觀整個 Android 體系結構,底層內核空間以 Linux Kernel 為核心,上層用戶空間以 C++/Java 組成的 Framework 層組成,通過系統呼叫來連接用戶空間和內核空間,而用戶空間又分為 Native 世界和 Java 世界,通過 JNI 技術進行連接,Native 世界的 init 行程是所有用戶行程的祖先,其 pid 為 1 ,init 行程通過決議 init.rc 檔案創建出 Zygote 行程,Zygote 行程人如其名,翻譯成中文就是 受精卵 的意思,它是 Java 世界的中的第一個行程,也是 Android 系統中的第一個 Java 行程,頗有盤古開天辟地之勢,
Zygote 創建的第一個行程就是 System Server,System Server 負責管理和啟動整個 Java Framework 層,創建完 System Server 之后,Zygote 就會完全進入受精卵的角色,等待進行無性繁殖,創建應用行程,所有的應用行程都是由 Zygote 行程 fork 而來的,稱之為 Java 世界的女媧也不足為過,
Zygote 的啟動程序是從 Native 層開始的,這里不會 Native 層作過多分析,直接進入其在 Java 世界的入口 ZygoteInit.main() :
public static void main(String argv[]) {
ZygoteServer zygoteServer = new ZygoteServer();
// Mark zygote start. This ensures that thread creation will throw
// an error.
ZygoteHooks.startZygoteNoThreadCreation();
// Zygote goes into its own process group.
// 設定行程組 ID
// pid 為 0 表示設定當前行程的行程組 ID
// gid 為 0 表示使用當前行程的 PID 作為行程組 ID
try {
Os.setpgid(0, 0);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to setpgid(0,0)", ex);
}
final Runnable caller;
try {
......
RuntimeInit.enableDdms(); // 啟用 DDMS
boolean startSystemServer = false;
String socketName = "zygote";
String abiList = null;
boolean enableLazyPreload = false;
for (int i = 1; i < argv.length; i++) { // 引數決議
if ("start-system-server".equals(argv[i])) {
startSystemServer = true;
} else if ("--enable-lazy-preload".equals(argv[i])) {
enableLazyPreload = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
abiList = argv[i].substring(ABI_LIST_ARG.length());
} else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
socketName = argv[i].substring(SOCKET_NAME_ARG.length());
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}
if (abiList == null) {
throw new RuntimeException("No ABI list supplied.");
}
// 1. 注冊服務端 socket,這里的 IPC 不是 Binder 通信
zygoteServer.registerServerSocketFromEnv(socketName);
// In some configurations, we avoid preloading resources and classes eagerly.
// In such cases, we will preload things prior to our first fork.
if (!enableLazyPreload) {
bootTimingsTraceLog.traceBegin("ZygotePreload");
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
SystemClock.uptimeMillis());
preload(bootTimingsTraceLog); // 2. 預加載操作
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
SystemClock.uptimeMillis());
bootTimingsTraceLog.traceEnd(); // ZygotePreload
} else {
Zygote.resetNicePriority(); // 設定執行緒優先級為 NORM_PRIORITY (5)
}
// Do an initial gc to clean up after startup
gcAndFinalize(); // 3. 強制進行一次垃圾收集
Zygote.nativeSecurityInit();
// Zygote process unmounts root storage spaces.
Zygote.nativeUnmountStorageOnInit();
ZygoteHooks.stopZygoteNoThreadCreation();
if (startSystemServer) {
// 4. 啟動SystemServer 行程
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
if (r != null) {
r.run(); // 由 RuntimeInit.java 中的 MethodAndArgsCaller 反射呼叫SystemServer 的 main() 方法
return;
}
}
Log.i(TAG, "Accepting command socket connections");
// The select loop returns early in the child process after a fork and
// loops forever in the zygote.
// 5. 回圈等待處理客戶端請求
caller = zygoteServer.runSelectLoop(abiList);
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with exception", ex);
throw ex;
} finally {
zygoteServer.closeServerSocket(); // 關閉并釋放 socket 連接
}
// We're in the child process and have exited the select loop. Proceed to execute the
// command.
if (caller != null) {
caller.run();
}
}
省去部分不是那么重要的代碼,ZygoteInit.main() 方法大致可以分為以下五個步驟:
registerServerSocketFromEnv, 注冊服務端 socket,用于跨行程通信,這里并沒有使用 Binder 通信,preload(),進行預加載操作gcAndFinalize(),在 forkSystemServer 之前主動進行一次垃圾回收forkSystemServer(),創建 SystemServer 行程runSelectLoop(),回圈等待處理客戶端發來的 socket 請求
上面基本上就是 Zygote 的全部使命了,下面按照這個流程來詳細分析,
registerServerSocketFromEnv
> ZygoteServer.java
void registerServerSocketFromEnv(String socketName) {
if (mServerSocket == null) {
int fileDesc;
final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
try {
// 從環境變數中獲取 socket 的 fd
String env = System.getenv(fullSocketName);
fileDesc = Integer.parseInt(env);
} catch (RuntimeException ex) {
throw new RuntimeException(fullSocketName + " unset or invalid", ex);
}
try {
FileDescriptor fd = new FileDescriptor();
fd.setInt$(fileDesc); // 設定檔案描述符
mServerSocket = new LocalServerSocket(fd); // 創建服務端 socket
mCloseSocketFd = true;
} catch (IOException ex) {
throw new RuntimeException(
"Error binding to local socket '" + fileDesc + "'", ex);
}
}
}
首先從環境變數中獲取 socket 的檔案描述符 fd,然后根據 fd 創建服務端 LocalServerSocket,用于 IPC 通信,這里的環境變數是在 init 行程創建 Zygote 行程時設定的,
preload()
> ZygoteInit.java
static void preload(TimingsTraceLog bootTimingsTraceLog) {
......
preloadClasses(); // 預加載并初始化 /system/etc/preloaded-classes 中的類
......
preloadResources(); // 預加載系統資源
......
nativePreloadAppProcessHALs(); // HAL?
......
preloadOpenGL(); // 預加載 OpenGL
......
preloadSharedLibraries(); // 預加載 共享庫,包括 android、compiler_rt、jnigraphics 這三個庫
preloadTextResources(); // 預加載文字資源
// Ask the WebViewFactory to do any initialization that must run in the zygote process,
// for memory sharing purposes.
// WebViewFactory 中一些必須在 zygote 行程中進行的初始化作業,用于共享記憶體
WebViewFactory.prepareWebViewInZygote();
warmUpJcaProviders();
sPreloadComplete = true;
}
preload() 方法主要進行一些類,資源,共享庫的預加載作業,以提升運行時效率,下面依次來看一下都預加載了哪些內容,
preloadClasses()
> ZygoteInit.java
private static void preloadClasses() {
......
InputStream is;
try {
// /system/etc/preloaded-classes
is = new FileInputStream(PRELOADED_CLASSES);
} catch (FileNotFoundException e) {
Log.e(TAG, "Couldn't find " + PRELOADED_CLASSES + ".");
return;
}
try {
BufferedReader br
= new BufferedReader(new InputStreamReader(is), 256);
int count = 0;
String line;
while ((line = br.readLine()) != null) {
// Skip comments and blank lines.
line = line.trim();
if (line.startsWith("#") || line.equals("")) {
continue;
}
try {
// Load and explicitly initialize the given class. Use
// Class.forName(String, boolean, ClassLoader) to avoid repeated stack lookups
// (to derive the caller's class-loader). Use true to force initialization, and
// null for the boot classpath class-loader (could as well cache the
// class-loader of this class in a variable).
Class.forName(line, true, null);
count++;
} catch (ClassNotFoundException e) {
Log.w(TAG, "Class not found for preloading: " + line);
} catch (UnsatisfiedLinkError e) {
Log.w(TAG, "Problem preloading " + line + ": " + e);
} catch (Throwable t) {
......
}
}
} catch (IOException e) {
Log.e(TAG, "Error reading " + PRELOADED_CLASSES + ".", e);
} finally {
IoUtils.closeQuietly(is);
......
}
}
只保留了核心邏輯代碼,讀取 /system/etc/preloaded-classes 檔案,并通過 Class.forName() 方法逐行加載檔案中宣告的類,提前預加載系統常用的類無疑可以提升運行時效率,但是這個預加載常用類的作業通常都會很重,搜索整個原始碼庫,在 /frameworks/base/config 目錄下發現一份 preloaded-classes 檔案,打開這個檔案,一共 6558 行,這就意味著要提前加載數千個類,這無疑會消耗很長時間,以增加 Android 系統啟動時間的代價提升了運行時的效率,
preloadResources()
> ZygoteInit.java
private static void preloadResources() {
final VMRuntime runtime = VMRuntime.getRuntime();
try {
mResources = Resources.getSystem();
mResources.startPreloading();
if (PRELOAD_RESOURCES) {
TypedArray ar = mResources.obtainTypedArray(
com.android.internal.R.array.preloaded_drawables);
int N = preloadDrawables(ar);
ar.recycle();
......
ar = mResources.obtainTypedArray(
com.android.internal.R.array.preloaded_color_state_lists);
N = preloadColorStateLists(ar);
ar.recycle();
if (mResources.getBoolean(
com.android.internal.R.bool.config_freeformWindowManagement)) {
ar = mResources.obtainTypedArray(
com.android.internal.R.array.preloaded_freeform_multi_window_drawables);
N = preloadDrawables(ar);
ar.recycle();
}
}
mResources.finishPreloading();
} catch (RuntimeException e) {
Log.w(TAG, "Failure preloading resources", e);
}
}
從原始碼中可知,主要加載的資源有:
com.android.internal.R.array.preloaded_drawables
com.android.internal.R.array.preloaded_color_state_lists
com.android.internal.R.array.preloaded_freeform_multi_window_drawables
preloadSharedLibraries()
> ZygoteInit.java
private static void preloadSharedLibraries() {
Log.i(TAG, "Preloading shared libraries...");
System.loadLibrary("android");
System.loadLibrary("compiler_rt");
System.loadLibrary("jnigraphics");
}
預加載了三個共享庫,libandroid.so 、libcompiler_rt.so 和 libjnigraphics.so ,
gcAndFinalize()
> ZygoteInit.java
static void gcAndFinalize() {
final VMRuntime runtime = VMRuntime.getRuntime();
/* runFinalizationSync() lets finalizers be called in Zygote,
* which doesn't have a HeapWorker thread.
*/
System.gc();
runtime.runFinalizationSync();
System.gc();
}
在 forkSystemServer() 之前會主動進行一次 GC 操作,
forkSystemServer()
主動呼叫 GC 之后,Zygote 就要去做它的大事 —— fork SystemServer 行程了,
> ZygoteInit.java
private static Runnable forkSystemServer(String abiList, String socketName,
......
/* Hardcoded command line to start the system server */
// 啟動引數
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server", // 行程名
"--runtime-args",
"--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
"com.android.server.SystemServer", // 加載類名
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
boolean profileSystemServer = SystemProperties.getBoolean(
"dalvik.vm.profilesystemserver", false);
if (profileSystemServer) {
parsedArgs.runtimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
}
/* Request to fork the system server process
* fork system_server 行程
*/
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.runtimeFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
// pid == 0 表示子行程,從這里開始進入 system_server 行程
if (pid == 0) {
if (hasSecondZygote(abiList)) { // 如果有第二個 Zygote
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket(); // 關閉并釋放從 Zygote copy 過來的 socket
return handleSystemServerProcess(parsedArgs); // 完成新創建的 system_server 行程的剩余作業
}
/**
* 注意 fork() 函式式一次執行,兩次回傳(兩個行程對同一程式的兩次執行),
* pid > 0 說明還是父行程,pid = 0 說明進入了子行程
* 所以這里的 return null 依舊會執行
*/
return null;
}
從上面的啟動引數可以看到,SystemServer 行程的 uid 和 gid 都是 1000,行程名是 system_server ,其最后要加載的類名是 com.android.server.SystemServer ,準備好一系列引數之后通過 ZygoteConnection.Arguments() 拼接,接著呼叫 Zygote.forkSystemServer() 方法真正的 fork 出子行程 system_server,
> Zygote.java
public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
VM_HOOKS.preFork();
// Resets nice priority for zygote process.
resetNicePriority();
int pid = nativeForkSystemServer(
uid, gid, gids, runtimeFlags, rlimits, permittedCapabilities, effectiveCapabilities);
// Enable tracing as soon as we enter the system_server.
if (pid == 0) {
Trace.setTracingEnabled(true, runtimeFlags);
}
VM_HOOKS.postForkCommon();
return pid;
}
native private static int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
最后的 fork() 操作是在 native 層完成的,再回到 ZygoteInit.forkSystemServer() 中執行 fork() 之后的邏輯處理:
if(pid == 0){
......
return handleSystemServerProcess(parsedArgs);
}
return null;
按正常邏輯思維,這兩處 return 只會執行一次,其實不然,fork() 函式是一次執行,兩次回傳,說的更嚴謹一點是 兩個行程對用一個程式的兩次執行,當 pid == 0 時,說明現在處于子行程,當 pid > 0 時,說明處于父行程,在剛 fork 出子行程的時候,父子行程的資料結構基本是一樣的,但是之后就分道揚鑣了,各自執行各自的邏輯,所以上面的代碼段中會有兩次回傳值,子行程 (system_server) 中會回傳執行 handleSystemServerProcess(parsedArgs) 的結果,父行程 (zygote) 會回傳 null,對于兩個不同的回傳值又會分別做什么處理呢?我們回到 ZygoteInit.main() 中:
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
// r == null 說明是在 zygote 行程
// r != null 說明是在 system_server 行程
if (r != null) {
r.run();
return;
}
}
// 回圈等待處理客戶端請求
caller = zygoteServer.runSelectLoop(abiList);
子行程 system_server 回傳的是一個 Runnable,執行 r.run(),然后就直接 return 了,而父行程 zygote 回傳的是 null,所以不滿足 if 的判斷條件,繼續往下執行 runSelectLoop ,父子行程就此分道揚鑣,各干各的事,
下面就來分析 runSelectLoop() 和 handleSystemServerProcess() 這兩個方法,看看 Zygote 和 SystemServer 這對父子行程繼續做了些什么作業,
handleSystemServerProcess
到這里其實已經脫離 Zygote 的范疇了,本準備放在下一篇 SystemServer 原始碼決議中再介紹,可是這里不寫又覺得 Zygote 介紹的不完整,索性就一并說了,
> ZygoteInit.java
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
// set umask to 0077 so new files and directories will default to owner-only permissions.
// umask一般是用在你初始創建一個目錄或者檔案的時候賦予他們的權限
Os.umask(S_IRWXG | S_IRWXO);
// 設定當前行程名為 "system_server"
if (parsedArgs.niceName != null) {
Process.setArgV0(parsedArgs.niceName);
}
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
// dex 優化操作
performSystemServerDexOpt(systemServerClasspath);
// Capturing profiles is only supported for debug or eng builds since selinux normally
// prevents it.
boolean profileSystemServer = SystemProperties.getBoolean(
"dalvik.vm.profilesystemserver", false);
if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
try {
prepareSystemServerProfile(systemServerClasspath);
} catch (Exception e) {
Log.wtf(TAG, "Failed to set up system server profile", e);
}
}
}
if (parsedArgs.invokeWith != null) { // invokeWith 一般為空
String[] args = parsedArgs.remainingArgs;
// If we have a non-null system server class path, we'll have to duplicate the
// existing arguments and append the classpath to it. ART will handle the classpath
// correctly when we exec a new process.
if (systemServerClasspath != null) {
String[] amendedArgs = new String[args.length + 2];
amendedArgs[0] = "-cp";
amendedArgs[1] = systemServerClasspath;
System.arraycopy(args, 0, amendedArgs, 2, args.length);
args = amendedArgs;
}
WrapperInit.execApplication(parsedArgs.invokeWith,
parsedArgs.niceName, parsedArgs.targetSdkVersion,
VMRuntime.getCurrentInstructionSet(), null, args);
throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
// 創建類加載器,并賦給當前執行緒
cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
/*
* Pass the remaining arguments to SystemServer.
*/
return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
/* should never reach here */
}
設定行程名為 system_server,執行 dex 優化,給當前執行緒設定類加載器,最后呼叫 ZygoteInit.zygoteInit() 繼續處理剩余引數,
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
......
// Redirect System.out and System.err to the Android log.
// 重定向 System.out 和 System.err 到 Android log
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit(); // 一些初始化作業
ZygoteInit.nativeZygoteInit(); // native 層初始化
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader); // 呼叫入口函式
}
重定向 Log,進行一些初始化作業,這部分不細說了,點擊文章開頭給出的原始碼鏈接,大部分都做了注釋,最后呼叫 RuntimeInit.applicationInit() ,繼續追進去看看,
> RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
......
final Arguments args = new Arguments(argv); // 決議引數
......
// 尋找 startClass 的 main() 方法,這里的 startClass 是 com.android.server.SystemServer
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
這里的 startClass 引數是 com.android.server.SystemServer,findStaticMain() 方法看名字就能知道它的作用是找到 main() 函式,這里是要找到 com.android.server.SystemServer 類的 main() 方法,
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
// 尋找 main() 方法
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Missing static main on " + className, ex);
} catch (SecurityException ex) {
throw new RuntimeException(
"Problem getting static main on " + className, ex);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
* 回傳一個 Runnable,在 Zygote 的 main() 方法中執行器 run() 方法
* 之前的版本是拋出一個例外,在 main() 方法中捕獲
*/
return new MethodAndArgsCaller(m, argv);
}
找到 main() 方法并構建一個 Runnable 物件 MethodAndArgsCaller ,這里回傳的 Runnable 物件會在哪里執行呢?又要回到文章開頭的 ZygoteInit.main() 函式了,在 forkSystemServer() 之后,子行程執行 handleSystemServerProcess() 并回傳一個 Runnable 物件,在 ZygoteInit.main() 中會執行其 run() 方法,
再來看看 MethodAndArgsCaller 的 run() 方法吧!
static class MethodAndArgsCaller implements Runnable {
/** method to call */
private final Method mMethod;
/** argument array */
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
public void run() {
try {
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException(ex);
}
}
}
就一件事,執行引數中的 method,這里的 method 就是 com.android.server.SystemServer 的 main() 方法,到這里,SystemServer 就要正式作業了,
其實在老版本的 Android 原始碼中,并不是通過這種方法執行 SystemServer.main() 的,老版本的 MethodAndArgsCaller 是 Exception 的子類,在這里會直接拋出例外,然后在 ZygoteInit.main() 方法中進行捕獲,捕獲之后執行其 run() 方法,
SystemServer 的具體分析就放到下篇文章吧,本篇的主角還是 Zygote !
看到這里,Zygote 已經完成了一件人生大事,范訓出了 SystemServer 行程,但是作為 “女媧” ,造人的任務還是停不下來,任何一個應用行程的創建還是離不開它的,ZygoteServer.runSlectLoop() 給它搭好了和客戶端之前的橋梁,
runSelectLoop
> ZygoteServer.java
Runnable runSelectLoop(String abiList) {
ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
// mServerSocket 是之前在 Zygote 中創建的
fds.add(mServerSocket.getFileDescriptor());
peers.add(null);
while (true) {
StructPollfd[] pollFds = new StructPollfd[fds.size()];
for (int i = 0; i < pollFds.length; ++i) {
pollFds[i] = new StructPollfd();
pollFds[i].fd = fds.get(i);
pollFds[i].events = (short) POLLIN;
}
try {
// 有事件來時往下執行,沒有時就阻塞
Os.poll(pollFds, -1);
} catch (ErrnoException ex) {
throw new RuntimeException("poll failed", ex);
}
for (int i = pollFds.length - 1; i >= 0; --i) {
if ((pollFds[i].revents & POLLIN) == 0) {
continue;
}
if (i == 0) { // 有新客戶端連接
ZygoteConnection newPeer = acceptCommandPeer(abiList);
peers.add(newPeer);
fds.add(newPeer.getFileDesciptor());
} else { // 處理客戶端請求
try {
ZygoteConnection connection = peers.get(i);
final Runnable command = connection.processOneCommand(this);
......
} catch (Exception e) {
......
}
}
}
}
mServerSocket 是 ZygoteInit.main() 中一開始就建立的服務端 socket,用于處理客戶端請求,一看到 while(true) 就肯定會有阻塞操作,Os.poll() 在有事件來時往下執行,否則就阻塞,當有客戶端請求過來時,呼叫 ZygoteConnection.processOneCommand() 方法來處理,
processOneCommand() 原始碼很長,這里就貼一下關鍵部分:
......
pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
parsedArgs.runtimeFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
parsedArgs.niceName, fdsToClose, fdsToIgnore, parsedArgs.startChildZygote,
parsedArgs.instructionSet, parsedArgs.appDataDir);
try {
if (pid == 0) {
// in child 進入子行程
zygoteServer.setForkChild();
zygoteServer.closeServerSocket();
IoUtils.closeQuietly(serverPipeFd);
serverPipeFd = null;
return handleChildProc(parsedArgs, descriptors, childPipeFd,
parsedArgs.startChildZygote);
} else {
// In the parent. A pid < 0 indicates a failure and will be handled in
// handleParentProc.
IoUtils.closeQuietly(childPipeFd);
childPipeFd = null;
handleParentProc(pid, descriptors, serverPipeFd);
return null;
}
} finally {
IoUtils.closeQuietly(childPipeFd);
IoUtils.closeQuietly(serverPipeFd);
}
乍一看是不是感覺有點眼熟?沒錯,這一塊的邏輯和 forkSystemServer() 很相似,只是這里 fork 的是普通應用行程,呼叫的是 forkAndSpecialize() 方法,中間的代碼呼叫就不在這詳細分析了,最后還是會呼叫到 findStaticMain() 執行應用行程的對應 main() 方法,感興趣的同學可以到我的原始碼專案 android_9.0.0_r45 閱讀相關檔案,注釋還是比較多的,
還有一個問題,上面只分析了 Zygote 接收到客戶端請求并回應,那么這個客戶端可能是誰呢?具體又是如何與 Zygote 通信的呢?關于這個問題,后續文章中肯定會寫到,關注我的 Github 倉庫 android_9.0.0_r45,所有文章都會第一時間同步過去,
總結
來一張時序圖總結全文 :

最后想說說如何閱讀 AOSP 原始碼和開源專案原始碼,我的看法是,不要上來就拼命死磕,一行一行的非要全部看懂,首先要理清脈絡,能大致的理出來一個時序圖,然后再分層細讀,這個細讀的程序中碰到不懂的知識點就得自己去挖掘,比如文中遇到的 forkSystemServer() 為什么會回傳兩次?當然,對于實在超出自己知識范疇的內容,也可以選擇性的暫時跳過,日后再戰,最后的最后,來篇技術博客吧!理清,看懂,表達,都會逐步加深你對原始碼的了解程度,還能分享知識,反饋社區,何樂而不為呢?
下篇文章會具體說說 SystemServer 行程具體都干了些什么,
文章首發微信公眾號:
秉心說, 專注 Java 、 Android 原創知識分享,LeetCode 題解,更多最新原創文章,掃碼關注我吧!

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/58632.html
標籤:Android
