Android Source Code Analysis (v) Zygote process

Source: Internet
Author: User

I. Preface:

NIT process –> zygote process –> systemserver process –> Launcher Desktop program-our app

Init process: Linux root process, Android system is based on Linux system, so it can be counted as the first process of the entire Android operating system;

Zygote process: Root process of Android system, main function: can function zygote process fork out systemserver process and various application processes;

Systemservice process: Mainly in this process to start the system of various services, such as activitymanagerservice,packagemanagerservice,windowmanagerservice services, etc.;

Launcher Desktop Program: is the desktop program that we usually see, it is actually an Android application, but this application is the system by default the first launch of the application.

Two. Zygote process

The Android system is based on the Linux kernel, and all processes in the Linux system are descendants of the Init process, that is, all processes are directly or indirectly forked out by the Init process. The zygote process is no exception, it is a system-initiated process created by the INIT process.
The init process typically invokes the main method of the Zygoteinit class when it starts the zygote process.

//Zygoteinit.java     Public Static voidMain (String argv[]) {zygoteserver zygoteserver=NewZygoteserver (); //Mark zygote start. This ensures that thread creation would throw//An error.zygotehooks.startzygotenothreadcreation (); //Zygote goes into its own process group.        Try{Os.setpgid (0, 0); } Catch(Errnoexception ex) {Throw NewRuntimeException ("Failed to Setpgid (0,0)", ex); }        Try {            //Report Zygote start time to Tron unless it is a runtime restart            if(!" 1 ". Equals (Systemproperties.get (" sys.boot_completed ")) {Metricslogger.histogram (NULL, "Boot_zygote_init",                        (int) Systemclock.elapsedrealtime ()); } String Boottimetag= Process.is64bit ()? "Zygote64timing": "Zygote32timing"; Boottimingstracelog Boottimingstracelog=NewBoottimingstracelog (Boottimetag, Trace.trace_tag_dalvik); Boottimingstracelog.tracebegin ("Zygoteinit");            Runtimeinit.enableddms (); //Start profiling the zygote initialization.Samplingprofilerintegration.start (); BooleanStartsystemserver =false; String Socketname= "Zygote"; String abilist=NULL; BooleanEnablelazypreload =false;  for(inti = 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 NewRuntimeException ("Unknown command line argument:" +Argv[i]); }            }            if(Abilist = =NULL) {                Throw NewRuntimeException ("No ABI list supplied."));            } zygoteserver.registerserversocket (Socketname); //in some configurations, we avoid preloading resources and classes eagerly. //in such cases, we'll preload things prior to our first fork.            if(!enablelazypreload) {Boottimingstracelog.tracebegin ("Zygotepreload");                Eventlog.writeevent (Log_boot_progress_preload_start, Systemclock.uptimemillis ());                Preload (Boottimingstracelog);                Eventlog.writeevent (Log_boot_progress_preload_end, Systemclock.uptimemillis ()); Boottimingstracelog.traceend (); //Zygotepreload}Else{zygote.resetnicepriority (); }            //Finish profiling the zygote initialization.Samplingprofilerintegration.writezygotesnapshot (); //Do a initial GC to clean up after startupBoottimingstracelog.tracebegin ("POSTZYGOTEINITGC");            Gcandfinalize (); Boottimingstracelog.traceend (); //POSTZYGOTEINITGCboottimingstracelog.traceend ();//Zygoteinit//Disable tracing So, forked processes do not inherit stale tracing tags from//Zygote.Trace.settracingenabled (false); //Zygote process unmounts root storage spaces.Zygote.nativeunmountstorageoninit (); //Set seccomp PolicySeccomp.setpolicy ();            Zygotehooks.stopzygotenothreadcreation (); if(startsystemserver) {startsystemserver (abilist, Socketname, zygoteserver); } log.i (TAG,"Accepting command socket connections");            Zygoteserver.runselectloop (abilist);        Zygoteserver.closeserversocket (); } Catch(Zygote.methodandargscaller caller) {Caller.run (); } Catch(Throwable ex) {LOG.E (TAG,"System Zygote died with exception", ex);            Zygoteserver.closeserversocket (); Throwex; }    }    //1.registerServerSocket//2. Call preload to load the resource,//3. Using Gcandfinalize to initialize the GC,//4. Start Systemserver,startsystemserver () to start the Systemserver service here. //5. Call Runselectloop to run the Looper selected by the zygote process,//6. Close and clean zygote sockets    
//Zygoteserver.java    /*** Registers a server socket for zygote command connections * *@throwsruntimeexception when open fails*/    voidRegisterserversocket (String socketname) {if(Mserversocket = =NULL) {            intFiledesc; FinalString Fullsocketname = Android_socket_prefix +Socketname; Try{String env=system.getenv (fullsocketname); Filedesc=Integer.parseint (env); } Catch(RuntimeException ex) {Throw NewRuntimeException (Fullsocketname + "unset or invalid", ex); }            Try{filedescriptor FD=NewFileDescriptor ();                fd.setint$ (FILEDESC); Mserversocket=NewLocalserversocket (FD); } Catch(IOException ex) {Throw NewRuntimeException ("Error binding to local socket '" + Filedesc + "'", ex); }        }    }
//Zygoteinit.java    Static voidpreload (Boottimingstracelog boottimingstracelog) {log.d (TAG,"Begin preload"); Boottimingstracelog.tracebegin ("Beginicucachepinning");        Beginicucachepinning (); Boottimingstracelog.traceend (); //beginicucachepinningBoottimingstracelog.tracebegin ("Preloadclasses"); //Initialize the class classes required in Zygotepreloadclasses (); Boottimingstracelog.traceend (); //preloadclassesBoottimingstracelog.tracebegin ("Preloadresources"); //Initializing system resourcespreloadresources (); Boottimingstracelog.traceend (); //preloadresourcesTrace.tracebegin (Trace.trace_tag_dalvik, "Preloadopengl"); //initializing OpenGLPreloadopengl ();        Trace.traceend (Trace.trace_tag_dalvik); //initializing the System librariespreloadsharedlibraries (); //initializing a text resourcepreloadtextresources (); //Ask The webviewfactory to does any initialization this must run in the zygote process,//For memory sharing purposes. //Initialize WebViewWebviewfactory.preparewebviewinzygote ();        Endicucachepinning ();        Warmupjcaproviders (); LOG.D (TAG,"End preload"); Spreloadcomplete=true; }
//let's go inside. Initialize WebView method//Webviewfactory.java    /*** Perform Any WebView loading preparations, must happen in the zygote.     * Currently, this means allocating address space to load the real JNI library later. */     Public Static voidPreparewebviewinzygote () {Try{system.loadlibrary ("Webviewchromium_loader"); LongAddressspacetoreserve =Systemproperties.getlong (Chromium_webview_vmsize_size_property, Chromium_webvie            W_default_vmsize_bytes); Saddressspacereserved=Nativereserveaddressspace (Addressspacetoreserve); if(saddressspacereserved) {if(DEBUG) {log.v (LogTag,"Address space reserved:" + addressspacetoreserve + "bytes"); }            } Else{log.e (LogTag,"Reserving" + Addressspacetoreserve + "bytes of address space failed"); }        } Catch(Throwable t) {//Log and discard errors at the-stage as we must not crash the zygote.LOG.E (LogTag, "error preparing native loader", T); }    }

Android Source Code Analysis (v) Zygote process

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.