重慶建網(wǎng)站的公司集中在哪里百度醫(yī)生
上一篇講了Zygote是如何收到啟動Application的啟動消息,并一步步進(jìn)入Fork(),下面來分析zygote fork啟動application后,application進(jìn)程后續(xù)處理操作,是如何真正的啟動的。
ZygoteInit.main():-->...caller = ZygoteServer.runSelectLoop();-->while(true) //死循環(huán)-->Zygoteconnection connection = peers.get(); Runnable command = connection.processOneCommand();//進(jìn)行進(jìn)程的處理,創(chuàng)建新進(jìn)程-->args = Zygote.readArgumentList(mSocketReader);//獲取socket命令參數(shù)ZygoteArguments parsedArgs = new ZygoteArguments();...各種參數(shù)解析中...pid = zygote.forkAndSpecialize();//Fork子進(jìn)程,得到一個(gè)新的pid.-->pid = nativeForkAndSpecialize(); //調(diào)用native層接口去forkif(pid == 0){ //子進(jìn)程}return pid;if(pid == 0) //子進(jìn)程:Application進(jìn)程{//關(guān)閉Zygote服務(wù)Socket:因?yàn)閒ork時(shí)復(fù)制出來的socket,對Application進(jìn)程來說,它沒有用。zygoteServer.closeServerSocket(); //application進(jìn)程可以正常運(yùn)行了。return handleProcessChild();-->ZygoteConnection.java:ZygoteInit.zygoteInit(parseArgs.xxx); //app進(jìn)程的啟動-->ZygoteInit.java:RuntimeInit.commonInit(); //初始化運(yùn)行環(huán)境ZygoteInit.nativeZygoteInit();//啟動Binder, 并在androidRuntime.cpp中注冊-->com_android_internal_os_ZygoetInit_ativeZygoteInit():-->gCurRuntime->onZygoteInit(); //通過JNI進(jìn)入Native-->//進(jìn)入app_main.cpp.onZygoteInit();//下面ProcessState對應(yīng)Application這個(gè)進(jìn)程實(shí)例,里面會初始化Binder-->sp<ProcessState> proc = ProcessState::self();-->在C++構(gòu)造函數(shù)初始化列表中:mDriverFD(open_driver(driver))//這里總結(jié)下,Application被Zygote Fork出來之后,進(jìn)入到Native層處理的目的是為了構(gòu)建Binder.//因?yàn)楹罄m(xù)的跨進(jìn)程通信,都需要借助Binder.后續(xù)將此Binder發(fā)給AMS,AMS拿到App的IBinder,才能//夠通過AMS的服務(wù)來與APP通信。proc->startThreadPool(); //啟動Binder線程池//里面通過反射創(chuàng)建程序入口函數(shù)的Method對象,并返回Runnable對象return RuntimeInit.applicationInit();//類名字,類參數(shù),加載器-->return findStaticMain(args.startClass, args.startArgs,classLoader);//通過反射拿到對應(yīng)類的main方法的Method對象:找到的就是ActivityThread.java.main();-->m = cl.getMethod("main",new class[]{string[].class});return 近回一個(gè)Runnable 對象。}else{ //zygote 進(jìn)程}...//Runnable對象返回到這里,對應(yīng)上面代碼中的Runnable command = connection.processOneCommand();后面//繼續(xù)接著返回,最后返回到上面代碼的caller = ZygoteServer.runSelectLoop();if(caller != null)caller.run(); //執(zhí)行返回的Runnable對象,進(jìn)入子進(jìn)程。-->RuntimeInit.java.MethodAndArgsCaller->run();-->mMethod.invoke();//java反射原理。(執(zhí)行的是ActivityThread.java的main())
分析時(shí)需要注意的是,底層調(diào)用linux fork()接口之后,會有兩個(gè)返回值,如果pid =0,表示返回的是子進(jìn)程,如果pid >0,返回的是父進(jìn)程(即zygote的程序運(yùn)行路線),父進(jìn)程(zygote進(jìn)程)可以得知子進(jìn)程的pid號。
補(bǔ)充一個(gè)要點(diǎn):ApplicationThread是什么?它其實(shí)是一個(gè)IApplicationThread.Stub對象,通過IBinder對象進(jìn)行跨進(jìn)程通信訪問時(shí),ApplicationThread本質(zhì)就是Binder線程池中的一個(gè)線程(關(guān)聯(lián)到上面代碼中的proc->startThreadPool() )