Android startup-a deep understanding of zygote 1

Source: Internet
Author: User
Tags signal handler

The previous http://www.bkjia.com/kf/201203/123061.html article introduced the Startup Process of the init process, including parsing init. the rc Script starts many important services based on the Content configuration: The Servicemanager and zygote processes lay the foundation for Android and build a real android space.

Process name process path

Zygote/system/bin/app_process

Servicemanager/system/bin/servicemanager

Bootanim/system/bin/bootanimation

Media/system/bin/mediaserver

...

In the native world, if this layer analyzes which service is not started, you can find the relevant process and print it. For better analysis, you can use the ps command to view the processes that are successfully started.

Two different worlds in android:

JAVA World: running JAVA programs based on dalvik virtual machines

NATIVE world: the native world is formed by using programs developed by C or C ++.

The following describes how to start zygote:

Code path: frameworks \ base \ cmds \ app_process

Startup parameters:

Service zygote/system/bin/app_process-Xzygote/system/bin -- zygote -- start-system-server

Int main (int argc, const char * const argv [])

{

// These are global variables in ProcessState. cpp

MArgC = argc;

MArgV = argv;

// Next arg is startup classname or "-- zygote"

If (I <argc ){

Arg = argv [I ++];

If (0 = strcmp ("-- zygote", arg) {// parameter value in init. rc

Bool startSystemServer = (I <argc )?

Strcmp (argv [I], "-- start-system-server") = 0: false;

SetArgv0 (argv0, "zygote ");

Set_process_name ("zygote"); // use prctl to modify the process name

Runtime. start ("com. android. internal. OS. ZygoteInit ",

StartSystemServer); // This is the real point !!!!
}

....

}

Create AndroidRuntime as follows:

Path: frameworks \ base \ core \ jni

Class AppRuntime: public AndroidRuntime

AppRuntime overload implements the onStarted (), onZygoteInit (), onExit () functions.

Runtime. start ("com. android. internal. OS. ZygoteInit", startSystemServer );

--> Call

/*

* 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 ".

*/

Void AndroidRuntime: start (const char * className, const bool startSystemServer)

{

// You can see this sentence again, indicating that the system has restarted.

LOGD ("\ n >>>>>>>>>>>>>>> AndroidRuntime START <\ n ");

 


// 1. Start the VM

/* Start the virtual machine */

If (startVm (& mJavaVM, & env )! = 0)

Goto bail;

 


// 2. register the jni Function

/*

* Register android functions.

*/

If (starregulatory (env) <0 ){

LOGE ("Unable to register all android natives \ n ");

Goto bail;

}

/*

3. Find the main function from the com. android. internal. OS. ZygoteInit class, that is, call

In the ZygoteInit. java class, main will enter the java World ....

*/

StartMeth = env-> GetStaticMethodID (startClass, "main ",

"([Ljava/lang/String;) V ");
Env-> CallStaticVoidMethod (startClass, startMeth, strArray );

}

 


Welcome to the JAVA World .....

The following describes the main function in the ZygoteInit class:

Path: frameworks \ base \ core \ java \ com \ android \ internal \ OS

Public static void main (String argv []) {

// 1. Create a listening socket with a port number of 50 for receiving

// ActivityManangerService request, Fork Application

RegisterZygoteSocket ();

// 2. Pre-load classes and resources. You can try to optimize the code here, but it is a little troublesome.

PreloadClasses ();

// 3. Garbage Collection

Gc ();

// 4. Start SystemServer, which will be explained below

StartSystemServer ();

// 5. process customer connections and requests, which are handled by ZygoteConnection. runOnce ().

RunSelectLoopMode ();

...

}

 


SystemServer analysis:

This process is the first process produced by zygote.

/**

* Prepare the arguments and fork for the system server process.

*/

Private static boolean startSystemServer ()

{

...

/* Hardcoded command line to start the system server */

String args [] = {

& Quot; -- setuid = 1000 & quot ",

"-- Setgid = 1000", "-- setgroups = 1001,1002, 1003,1004, 1005,1006, 1007,1008, 1009,1010, 3001,3002, 3003 ",

"-- Capabilities = 1300000352,1300000352 ",

"-- Runtime-init ",

"-- Nice-name = system_server", // process name

"Com. android. server. SystemServer", // class name

};

// Parse parameters

ParsedArgs = new ZygoteConnection. Arguments (args );

/* Request to fork the system server process */

Pid = Zygote. forkSystemServer (

ParsedArgs. uid, parsedArgs. gid,

ParsedArgs. gids, debugFlags, null );

/* For child process */

If (pid = 0 ){

HandleSystemServerProcess (parsedArgs); // later

}

}

-->

ForkSystemServer this is a jni function called:

\ Dalvik \ vm \ native \ dalvik_system_Zygote.c

Static void Dalvik_dalvik_system_Zygote_forkSystemServer (

Const u4 * args, JValue * pResult)

{

Pid_t pid;

// Generate a sub-process based on the fork parameter. If one call is successful, two values are returned. The sub-process returns 0 and the parent process returns the sub-process ID. Otherwise, error-1 is returned.

Pid = forkAndSpecializeCommon (args );

If (pid> 0 ){

GDvm. systemServerPid = pid;

/* There is a slight window that the system server process has crashed

* But it went unnoticed because we haven't published its pid yet. So

* We recheck here just to make sure that all is well.

*/

If (waitpid (pid, & status, WNOHANG) = pid ){

LOGE ("System server process % d has died. Restarting Zygote! ", Pid );

Kill (getpid (), SIGKILL );

}

/*

This indicates that the SystemServer process exits, and its parent process is Zygote. Therefore, the Zygote process is killed, that is, both of them are exited ....

*/

}

}

 


Zygote is closely related to SystemServer. Here is a small processing logic:

Static pid_t forkAndSpecializeCommon (const u4 * args)

{

SetSignalHandler ();

}

-->

Static void setSignalHandler ()

{

Int err;

Struct sigaction sa;

Memset (& sa, 0, sizeof (sa ));

Sa. sa_handler = sigchldHandler; // a signal processing function is installed here.

Err = sigaction (SIGCHLD, & sa, NULL );

...

}

Signal processing functions:

/*

* This signal handler is for zygote mode, since the zygote

* Must reap its children

*/

Static void sigchldHandler (int s)

{

Pid_t pid;

While (pid = waitpid (-1, & status, WNOHANG)> 0 ){

/*

* If the just-crashed process is the system_server, bring down zygote

* So that it is restarted by init and system server will be restarted

* From there.

*/

If (pid = gDvm. systemServerPid ){

LOG (LOG_INFO, ZYGOTE_LOG_TAG,

"Exit zygote because system server (% d) has terminated \ n ",

(Int) pid );

Kill (getpid (), SIGKILL );

}

}

...

}

 


There are too many content in the Zygote startup process. The next article explains the process from handleSystemServerProcess

From andyhuabing's column

Related Article

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.