本文基於 Android 9.0 , 代碼倉庫地址 : android_9.0.0_r45java
文中源碼連接:linux
Zygote.javaandroid
ZygoteServer.javagithub
RuntimeInit.java數據結構
仔細看看下面這張 Android 體系圖,找一下 Zygote
在什麼地方。app
上圖來自 Gityuan 博客 。socket
縱觀整個 Android 體系結構,底層內核空間以 Linux Kernel 爲核心,上層用戶空間以 C++/Java 組成的 Framework 層組成,經過系統調用來鏈接用戶空間和內核空間。而用戶空間又分爲 Native 世界和 Java 世界,經過 JNI 技術進行鏈接。Native 世界的 init
進程是全部用戶進程的祖先,其 pid 爲 1 。init
進程經過解析 init.rc
文件建立出 Zygote
進程,Zygote
進程人如其名,翻譯成中文就是 受精卵 的意思。它是 Java 世界的中的第一個進程,也是 Android 系統中的第一個 Java 進程,很有盤古開天闢地之勢。ide
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 的所有使命了,下面按照這個流程來詳細分析。
> 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 進程時設置的。
> 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()
方法主要進行一些類,資源,共享庫的預加載工做,以提高運行時效率。下面依次來看一下都預加載了哪些內容。
> 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 系統啓動時間的代價提高了運行時的效率。
> 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
> 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
。
> 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 操做。
主動調用 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
這對父子進程繼續作了些什麼工做。
到這裏其實已經脫離 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()
給它搭好了和客戶端以前的橋樑。
> 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 題解。更多最新原創文章,掃碼關注我吧!