Zygote process "3"--systemserver born

Source: Internet
Author: User

Welcome reprint. Reprint Please specify: HTTP://BLOG.CSDN.NET/ZHGXHUAA


Several major events were made in the main () method of Zygoteinit. One of them is to start the systemserver process. The code is as follows:

@/frameworks/base/core/java/com/android/internal/os/zygoteinit.java

    public static void Main (String argv[]) {        try {        ...            if (Argv[1].equals ("Start-system-server")) {                startsystemserver ();//Start system_server process            } else if (!argv[1]. Equals ("")) {                throw new RuntimeException (Argv[0] + usage_string);            }            ......    }

The implementation of the Startsystemserver method is as follows:

@/frameworks/base/core/java/com/android/internal/os/zygoteinit.java
    /** * Prepare The arguments and fork for the system server process. */Private static Boolean Startsystemserver () throws Methodandargscaller, RuntimeException {long cap Abilities = Posixcapabilitiesasbits (Osconstants.cap_kill, Osconstants.cap_net_admin, OsC Onstants. Cap_net_bind_service, Osconstants.cap_net_broadcast, Osconstants.cap_net_raw, osconstants . Cap_sys_module, Osconstants.cap_sys_nice, Osconstants.cap_sys_resource, osconstants.cap_s        Ys_time, Osconstants.cap_sys_tty_config); /* 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,1032,3001,3002,3003,3006,300            7 ","--capabilities= "+ capabilities +", "+ capabilities,"--runtime-init ","--nice-name=system_server", "Com.android.server.SystemServer",};        Zygoteconnection.arguments Parsedargs = null;        int pid;            try {Parsedargs = new zygoteconnection.arguments (args);            Zygoteconnection.applydebuggersystemproperty (Parsedargs);            Zygoteconnection.applyinvokewithsystemproperty (Parsedargs);                    /* Request to fork the system server process */pid = Zygote.forksystemserver (//create System_server process as fork) Parsedargs.uid, Parsedargs.gid, Parsedargs.gids, Parsedargs.debugflags , NULL, Parsedargs.permittedcapabilities, Parsedargs.effectivecap        abilities);        } catch (IllegalArgumentException ex) {throw new RuntimeException (ex); }/* for child process */if (PID = = 0) {//pid==0 description in subprocess, parent process is zygote handlesystemserverprocess (par        Sedargs);     }   return true; }
The required number of fork Systemserver is set first in the Startsystemserver. Then through the Forksystemserver method fork out the systemserver process, finally through the handlesystemserverprocess to deal with the new process of rehabilitation matters.

First look at the number of references:

1, setuid=1000, here 1000 stands for system_uid. That is, the system process, the description of the process ID can be seen:/frameworks/base/core/java/android/os/process.java.

2, Nice-name=system_server said the development process is named "System_server"

3, Com.android.server.SystemServer represents the position of the Systemserver class.

Next look at the implementation of Forksystemserver:

@/libcore/dalvik/src/main/java/dalvik/system/zygote.java

    /** * Special method to start the system server process. In addition to the * common actions performed on Forkandspecialize, the PID of the child * process is recorded suc     H that the death of the child process would cause * zygote to exit. * * @param uid The UNIX uid that the new process should setuid () through * fork () ing and and before spawning any     Threads. * @param gid the UNIX gid that the new process should setgid () to After * fork () ing and and before spawning any thread S. * @param gids Null-ok;     A list of UNIX Gids that the new process should * setgroups () through fork and before spawning any threads.     * @param debugflags bit flags that enable debugging features.     * @param rlimits Null-ok An array of rlimit tuples, with the second * dimension have a length of 3 and representing * (Resource, rlim_cur, Rlim_max).     These is set via the POSIX * SETRLIMIT (2) call. * @param permittedcapabilities argument for Setcap () * @param effectivecapabilities argument for Setcap () * * @return 0 if the-the child, PID of the     * If this is the parent, or-1 on error. */public static int forksystemserver (int uid, int gid, int[] gids, int debugflags, int[][] rlimits, long PE        Rmittedcapabilities, Long effectivecapabilities) {prefork (); int pid = Nativeforksystemserver (uid, GID, Gids, DebugFlags, Rlimits, Permittedcapabilities, Effectivecapa        Bilities);        Postfork ();    return PID; } native public static int nativeforksystemserver (int uid, int. GID, int[] gids, int debugflags, int[][] Rlim Its, long permittedcapabilities, long effectivecapabilities);
Nativeforksystemserver is finally implemented by JNI and the code is:

@/dalvik/vm/native/dalvik_system_zygote.cpp

/* * native public static int nativeforksystemserver (int uid, int gid, *     int[] gids, int debugflag S, int[][] rlimits, *     Long permittedcapabilities, long effectivecapabilities);  */static void Dalvik_dalvik_system_zygote_forksystemserver (        const u4* args, jvalue* pResult) {    pid_t pid;    pid = Forkandspecializecommon (args, true);   /* The zygote process checks whether the C Hild process has a died or not. */    if (pid > 0) {//pid greater than 0, description is in parent process         int status;        Alogi ("System server process%d has been created", PID);        gdvm.systemserverpid = pid;    &N Bsp  /* There is a slight window, the system server process has crashed         * but it we NT unnoticed because we haven ' t published its PID yet. so         * We recheck here just to MAke sure that's well.         */        if (Waitpid (PID, &status, WN Ohang) = = pid) {//block. Wait for the System_server process             Aloge ("System server process%d has died. Restarting zygote! ", PID);            Kill (Getpid (), SIGKILL);//Once the above waits to return. Indicates that the process PID (System_server) has been terminated, at which point Zygote kills itself        }   }    return_int (PID);}
Can see that dalvik_dalvik_system_zygote_forksystemserver will call Forkandspecializecommon to fork out the system_server process. Here are the last words to pay attention to, after fork out System_server. Zygote will call Waitpid to wait for the termination of System_server, once the system_server is found to terminate, Zygote immediately commit suicide.

Next look at the implementation of Handlesystemserverprocess:

@/frameworks/base/core/java/com/android/internal/os/zygoteinit.java

    /**     * Finish remaining work for the newly forked system server process.    &NB sp;*/    private static void Handlesystemserverprocess (            ZYGOTECONNECTI On. Arguments Parsedargs)             throws Zygoteinit.methodandargscaller {    &NBSP ;   Closeserversocket ()//close socket  copied from zygote      //set Umask to 0077 so new files and Directo Ries'll default to Owner-only permissions.        Libcore.os.umask (S_irwxg | S_IRWXO)///Set default permissions for the file, remove all other privileges         if (parsedargs.nicename! = null) {        & nbsp   Process.setargv0 (parsedargs.nicename);//system_server       }        IF (Parsedargs.invokewith! = null) {            wrapperinit.execapplication (parsedargs.invokewith,          &NBsp         Parsedargs.nicename, parsedargs.targetsdkversion,            &N Bsp       NULL, Parsedargs.remainingargs);       } else {        &NBSP ;  /*             * Pass The remaining arguments to systemserver.    &NBS P        */            Runtimeinit.zygoteinit ( Parsedargs.targetsdkversion, Parsedargs.remainingargs);       }       /* Should never reach here */   }

The above code uses the Umask function in Linux. Ambiguous readers are able to participate in: Http://hi.baidu.com/fengyun409/item/82cd158ffe7f67c8b17154e7.

The following continues to see the implementation of the Runtimeinit.zygoteinit method:

@/frameworks/base/core/java/com/android/internel/os/runtimeinit.java

    /** * The main function called when started through the zygote process. This * could is unified with main (), if the native code in Nativefinishinit () * were rationalized with Zygote star tup.<p> * * Current recognized args: * <ul> * <li> <code> [--] <start class n ame> <args> * </ul> * * @param targetsdkversion target SDK version * @param argv arg strin GS */public static final void zygoteinit (int targetsdkversion, string[] argv) throws Zygoteinit.methoda        Ndargscaller {if (DEBUG) slog.d (TAG, "runtimeinit:starting application from Zygote"); Redirectlogstreams ();//redirect System.out and System.err output to Android's log system/* * Initialize some system properties, the most important of which is to set a non-catching exception of H         Andler. * When the code has any unknown exception, it will run, * the students who have debugged the Android code often see the "* * * FATAL EXCEPTION in SYSTEM PROCESS" printing is from here */Comm        OnInit (); /* * will finally call App_main's onzygoteinit function * thisThe role of the nativezygoteinit is to introduce binders into the new process.        The new process will be able to use the binder process to communicate with */Nativezygoteinit (); Applicationinit (Targetsdkversion, argv);//Application initialization}
Does this function seem familiar? Yes, in the "Zygote process" 2 "--zygote Division" we've seen that the zygote process calls this method to process the creation of a subprocess when it receives a request to create a process activitymanagerservice request.

    private static void Applicationinit (int targetsdkversion, string[] argv) throws Zygoteinit.methodandargscal ler {//If the application calls System.exit (), terminate the process//immediately without running any SH  Utdown Hooks.  It is not a possible to//shutdown an Android application gracefully. Among other things, the//Android runtime shutdown hooks Close the Binder driver, which can cause//Leftov        Er running threads to crash before the process actually exits.        Nativesetexitwithoutcleanup (TRUE); We want to is fairly aggressive about the heap utilization, to avoid//holding-a lot of memory that isn ' t nee        Ded.        Vmruntime.getruntime (). Settargetheaputilization (0.75f);        Vmruntime.getruntime (). Settargetsdkversion (targetsdkversion);        Final Arguments args;        try {args = new Arguments (argv);   } catch (IllegalArgumentException ex) {SLOG.E (TAG, Ex.getmessage ());         Let the process exit return; }//Remaining arguments is passed to the start class ' s static main Invokestaticmain (Args.startclass, args.    Startargs); }

So, this is different from the zygote split: The value of Args.startclass here is com.android.server.SystemServer.

Then we all know it. The main function of the Systemserver class will be called.

@/frameworks/base/services/java/com/android/server/systemserver.java

    public static void Main (string[] args) {if (System.currenttimemillis () < Earliest_supported_time) { If a device ' s clock is before 1970 (before 0), a lot of//APIs crash dealing with negative numbers, not ably//java.io.file#setlastmodified, so instead we fake it and//hope this time from cell towers O            R NTP fixes it//shortly. SLOG.W (TAG, "System clock is before 1970;            Setting to 1970. "); Systemclock.setcurrenttimemillis (earliest_supported_time);//Initialize System time} if (Samplingprofilerintegration.isenab            LED ()) {Samplingprofilerintegration.start ();            Timer = new timer (); Timer.schedule (New TimerTask () {@Override public void run () {SAMPLINGPR                Ofilerintegration.writesnapshot ("System_server", null);        }}, Snapshot_interval, Snapshot_interval); }//Mmmmmm ... More memory!       Dalvik.system.VMRuntime.getRuntime (). Cleargrowthlimit (); The system server has a to run all of the time, so it needs to be/as efficient as possible with its memory USAG        E. vmruntime.getruntime (). Settargetheaputilization (0.8f);        Environment.setuserrequired (TRUE);        System.loadlibrary ("Android_servers");//load into Android_servers library slog.i (TAG, "entered the Android system server!");        Initialize native Services. Nativeinit ();//Initialize native service//This used-be-it own separate thread, but now it's//Just the loop        We run on the main thread.        Serverthread thr = new Serverthread ();    Thr.initandloop (); }
The libandroid_servers.so library is loaded in main and then called Nativeinit to initialize the service of the native layer.

    /**     * Called to initialize native system services.     *    /private static native void Nativeinit ();
@/frameworks/base/services/jni/com_android_server_systemserver.cpp
static void Android_server_systemserver_nativeinit (jnienv* env, Jobject clazz) {    char Propbuf[property_value_max] ;    Property_get ("System_init.startsensorservice", Propbuf, "1");    if (strcmp (Propbuf, "1") = = 0) {        //Start the Sensor service        sensorservice::instantiate ();    }}
It can be seen that the sensor service is initialized only, which differs from the previous code in the earlier version of Android. The initialization of the service is divided into two init1 and init2 processes. The init of the native layer service (Surfaceflinger, Audioflinger, etc.) is primarily responsible for the initialization of the Java Layer service, Init2.

The Initandloop of the Serverthread class is called at the end of the main method to initialize the system service. This function is longer, and the code is not copied here.


Well, the birth of Systemserver is over.







Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Zygote process "3"--systemserver born

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.