2025-05-23

上一節/kf/201203/123062.html 說到 使用 Zygote.forkSystemServer 利用 fork 生成 SystemServer進程,那個這個進程到底幹瞭哪些事情呢?

下面從 handleSystemServerProcess 處理流程開始講解

代碼片段如下:

/* 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);

}

–>

private static void handleSystemServerProcess(

ZygoteConnection.Arguments parsedArgs)

{

// 關閉哪些從 Zygote 繼承來的 socket

closeServerSocket();

// 這裡調用到 zygoteInit函數

RuntimeInit.zygoteInit(parsedArgs.remainingArgs);

}

RuntimeInit.java @ frameworks\base\core\java\com\android\internal\os

public static final void zygoteInit(String[] argv){

// 這裡調用到 JNI 函數中去瞭

zygoteInitNative();

// 調用到startClass com.android.server.SystemServer 的main函數

invokeStaticMain(startClass, startArgs);

}

–>

zygoteInitNative @ frameworks\base\core\jni

調用到 onZygoteInit @frameworks\base\cmds\app_process\app_main.cpp

    virtual void onZygoteInit()

    {

        sp<ProcessState> proc = ProcessState::self();

        if (proc->supportsProcesses()) {

            LOGV("App process: starting thread pool.\n");

            proc->startThreadPool(); // 啟動線程,建立 binder 通訊

        }

}

ok, 這個流程清楚瞭,下面我們重點看看 native system_server進程如何啟動?

Main @ frameworks\base\services\java\com\android\server\SystemServer.java

public static void main(String[] args) {

System.loadLibrary("android_servers");

init1(args);

}

這裡 init1 是個 native 函數:

system_init @ frameworks\base\cmds\system_server\library\system_init.cpp

extern "C" status_t system_init()

{

LOGI("Entered system_init()");

// Start the SurfaceFlinger

SurfaceFlinger::instantiate();

runtime->callStatic("com/android/server/SystemServer", "init2");

}

這裡又調用到

init2 @ frameworks\base\services\java\com\android\server\SystemServer.java

public static final void init2() {

Thread thr = new ServerThread();

thr.setName("android.server.ServerThread");

thr.start();

}

這裡啟動瞭一個 ServerThread 線程並調用其start() 函數,其實也就是調用

ServerThread 線程的 run() 函數

public void run() {

     Slog.i(TAG, "Entropy Service");

     ServiceManager.addService("entropy", new EntropyService());

     Slog.i(TAG, "Power Manager");

     power = new PowerManagerService();

     ServiceManager.addService(Context.POWER_SERVICE, power);

 // 最後進入到 loop 消息循環中處理消息瞭。。。。

        Looper.loop();

        Slog.d(TAG, "System ServerThread is exiting!");

}

Oh , 原來就是在就裡將很多重要的系統服務依次加入到ServiecManager中,至此整個 SystemServer 進程啟動完成。

 

總結一下,重要執行過程如下:

  

摘自  andyhuabing的專欄 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *