瞭解了init進程和init.rc之後,來看一下zygote。
init.rc文件中
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
class main
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart media
onrestart restart netd
/system/bin/app_process -Xzygote /system/bin --zygote --start-system-server 程序位置及參數/system/bin/app_process代碼在frameworks/base/cmds/app_process/目錄下,入口主函數是app_main.cpp的main()函數。
根據代碼,設置了參數--zygote --start-system-server,最終會調用
AppRuntime runtime;
runtime.start("com.android.internal.os.ZygoteInit", "start-system-server");
AppRuntime也在app_main.cpp文件中定義,繼承了AndroidRuntimeclass AppRuntime : public AndroidRuntime
AndroidRuntime類在frameworks/base/core/jni/AndroidRuntime.cpp文件中定義。/*
* Start the Android runtime. This involves starting the virtual machine
* and calling the "static void main(String[] args)" method in the class
* named by "className".
*
* Passes the main function two arguments, the class name and the specified
* options string.
*/
void AndroidRuntime::start(const char* className, const char* options)
{
/* start the virtual machine */
JniInvocation jni_invocation;
jni_invocation.Init(NULL);
JNIEnv* env;
if (startVm(&mJavaVM, &env) != 0) {
return;
}
onVmCreated(env);
/*
* Register android functions.
*/
if (startReg(env) < 0) {
ALOGE("Unable to register all android natives\n");
return;
}
/*
* We want to call main() with a String array with arguments in it.
* At present we have two arguments, the class name and an option string.
* Create an array to hold them.
*/
jclass stringClass;
jobjectArray strArray;
jstring classNameStr;
jstring optionsStr;
stringClass = env->FindClass("java/lang/String");
assert(stringClass != NULL);
strArray = env->NewObjectArray(2, stringClass, NULL);
assert(strArray != NULL);
classNameStr = env->NewStringUTF(className);
assert(classNameStr != NULL);
env->SetObjectArrayElement(strArray, 0, classNameStr);
optionsStr = env->NewStringUTF(options);
env->SetObjectArrayElement(strArray, 1, optionsStr);
/*
* Start VM. This thread becomes the main thread of the VM, and will
* not return until the VM exits.
*/
char* slashClassName = toSlashClassName(className);
jclass startClass = env->FindClass(slashClassName);
if (startClass == NULL) {
ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
/* keep going */
} else {
jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
"([Ljava/lang/String;)V");
if (startMeth == NULL) {
ALOGE("JavaVM unable to find main() in '%s'\n", className);
/* keep going */
} else {
env->CallStaticVoidMethod(startClass, startMeth, strArray);
}
}
free(slashClassName);
ALOGD("Shutting down VM\n");
if (mJavaVM->DetachCurrentThread() != JNI_OK)
ALOGW("Warning: unable to detach main thread\n");
if (mJavaVM->DestroyJavaVM() != 0)
ALOGW("Warning: VM did not shut down cleanly\n");
}
這個函數的作用是啓動Android系統運行時庫,它主要做了三件事情,
一是調用函數startVM啓動虛擬機,
二是調用函數startReg註冊JNI方法,
三是調用了com.android.internal.os.ZygoteInit類的main函數。
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static void main(String argv[]) {
try {
......
registerZygoteSocket();//創建一個socket接口,用來和ActivityManagerService通訊
preload();
// Do an initial gc to clean up after startup
gc();
if (argv[1].equals("start-system-server")) {
startSystemServer();//啓動SystemServer
}
//通過Select方式監聽端口,即異步讀取消息,死循環,沒有消息則一直阻塞在那裏。
//在前面創建的socket接口上等待ActivityManagerService請求創建新的應用程序進程。
runSelectLoop();
closeServerSocket();
} catch (MethodAndArgsCaller caller) {
caller.run();
} catch (RuntimeException ex) {
...
}
}
startSystemServer() 創建SystemServer進程
/**
* Prepare the arguments and fork for the system server process.
*/
private static boolean startSystemServer() throws MethodAndArgsCaller, RuntimeException {
...
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
...
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (pid == 0) {
handleSystemServerProcess(parsedArgs);
}
return true;
}
startSystemServer()先配置啓動參數ZygoteConnection.Arguments parsedArgs,然後調用Zygote.forkSystemServer()libcore/dalvik/src/main/java/dalvik/system/Zygote.java
forkSystemServer()
nativeForkSystemServer()
dalvik/vm/native/dalvik_system_Zygote.cpp
Dalvik_dalvik_system_Zygote_forkSystemServer()
forkAndSpecializeCommon()
最終調用linux系統調用fork() 創建SystemServer進程。pid = Zygote.forkSystemServer() 這裏返回兩個進程id,
1、父進程(Zygote)的返回值pid是創建的子進程的id,大於0,直接返回到ZygoteInit.main()函數中,繼續執行runSelectLoop();
2、子進程(SystemServer)的返回值pid爲0,會調用handleSystemServerProcess(parsedArgs);做一些初始化操作,最後調用到RuntimeInit.invokeStaticMain()函數。
frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
private static void invokeStaticMain(String className, String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
......
Class<?> cl;
cl = Class.forName(className);
Method m;
m = cl.getMethod("main", new Class[] { String[].class });
......
/*
* 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.
*/
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
拋出異常ZygoteInit.MethodAndArgsCaller,會返回到ZygoteInit.main()函數異常處理,執行caller.run();根據ZygoteInit.startSystemServer()函數中的啓動參數
/* 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,1032,3001,3002,3003,3006,3007",
"--capabilities=" + capabilities + "," + capabilities,
"--runtime-init",
"--nice-name=system_server",
"com.android.server.SystemServer",
};
caller.run()最終會調用到com.android.server.SystemServer的main()函數,即 SystemServer的入口函數。到此,Zygote進程完成創建SystemServer進程,SystemServer進程由com.android.server.SystemServer.main()開始繼續運行,而Zygote進程繼續執行runSelectLoop()。
下面來看一下ZygoteInit.runSelectLoop()函數都做了什麼。
private static void runSelectLoop() throws MethodAndArgsCaller {
...
while (true) {//死循環,Zygote變爲守護進程
int index;
...
try {
fdArray = fds.toArray(fdArray);
/*
* selectReadable()函數的返回值有三種。
* -1: 代表着內部錯誤
* 0: 代表着沒有可處理的連接,因此會以Socket服務端口
* 重新建立一個ZygoteConnection對象,並等待客戶端的請求
* >0: 代表着還有沒有處理完的連接請求,
* 因此需要先處理該請求,而暫時不需要建立新的連接等待
*/
index = selectReadable(fdArray);
} catch (IOException ex) {
throw new RuntimeException("Error in select()", ex);
}
if (index < 0) {
throw new RuntimeException("Error in select()");
} else if (index == 0) {//<span><span class="comment">構造一個ZygoteConnection對象,並將其加入到peers列表中</span></span>
ZygoteConnection newPeer = acceptCommandPeer();
peers.add(newPeer);
fds.add(newPeer.getFileDesciptor());
} else {//<span><span class="comment">處理當前socket消息</span></span>,<span><span class="comment">調用ZygoteConnection的runOnce</span></span>()
boolean done;
done = peers.get(index).runOnce();
if (done) {
peers.remove(index);
fds.remove(index);
}
}
}
}
Zygote變爲一個守護進程,通過selectReadable()監聽socket連接請求。(這裏具體是誰會請求連接,後續研究)
監聽到連接請求,selectReadable()返回,就會調用ZygoteConnection的runOnce()函數。
frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
boolean runOnce() throws ZygoteInit.MethodAndArgsCaller {
...
try {
parsedArgs = new Arguments(args);//這裏的args參數是從socket中讀取的,也就是說是客戶端傳過來的
...
pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
parsedArgs.niceName);
} catch (...) {
...
}
try {
if (pid == 0) {
// in child
...
handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
// should never get here, the child is expected to either
// throw ZygoteInit.MethodAndArgsCaller or exec().
return true;
} else {
// in parent...pid of < 0 means failure
...
return handleParentProc(pid, descriptors, serverPipeFd, parsedArgs);
}
} finally {
...
}
}
runOnce()調用Zygote.forkAndSpecialize()libcore/dalvik/src/main/java/dalvik/system/Zygote.java
forkAndSpecialize()
nativeForkAndSpecialize()
dalvik/vm/native/dalvik_system_Zygote.cpp
Dalvik_dalvik_system_Zygote_forkAndSpecialize()
forkAndSpecializeCommon()
類似於上面的Zygote.forkSystemServer(),最後調用linux系統調用fork() 創建新的進程。這裏創建進程的參數是從socket中讀取的,也就是說是客戶端傳過來的。
創建新進程完成後,
父進程(Zygote)調用handleParentProc()處理一些事情後,返回ZygoteInit.runSelectLoop(),進入下一次循環,監聽連接請求。
子進程調用handleChildProc(),最後調用ZygoteInit.invokeStaticMain()函數(和RuntimeInit.invokeStaticMain()一樣),拋出異常ZygoteInit.MethodAndArgsCaller,返回到ZygoteInit.main()函數異常處理,執行caller.run(); 從而子進程跳出ZygoteInit.runSelectLoop()的死循環,去執行新的入口main()函數,開始新的進程人生。
總結:
Zygote進程由init進程啓動後,先創建SystemServer進程,然後變成守護進程,監聽socket請求,繼續創建其他進程。
遺留問題:
1、SystemServer進程創建後,SystemServer 由 com.android.server.SystemServer.main() 開始後續流程
2、Zygote變爲守護進程後,誰會發起socket連接請求創建新進程
題外知識:
Socket編程中有兩種方式去觸發Socket數據讀操作。一種是使用listen()監聽某個端口,然後調用read()去從這個端口上讀數據,這種方式被稱爲阻塞式讀操作,因爲當端口沒有數據時,read()函數將一直等待,直到數據準備好後才返回;另一種是使用select()函數將需要監測的文件描述符作爲select()函數的參數,然後當該文件描述符上出現新的數據後,自動觸發一箇中斷,然後在中斷處理函數中再去讀指定文件描述符上的數據,這種方式被稱爲非阻塞式讀操作。LocalServerSocket中使用的正是後者,即非阻塞讀操作。
參考:
http://www1.huachu.com.cn/read/readbookinfo.asp?sectionid=1000006113
http://blog.csdn.net/zhgxhuaa/article/details/24584807