Android Zygote Fork

Zygote

zygote 孵化器是 Android 应用进程的模板,通过其 fork 出来。 Zygote初始化最后进入 select 循环, 等待客户端的请求 fork 应用进程。

Android Zygote Fork_第1张图片

frameworks/base/core/java/com/android/internal/os/ZygoteServer.java

Runnable runSelectLoop(String abiList) {
    ......
    while(true) {
        StructPollfd[] pollFds = new StructPollfd[fds.size()];
        ......
        try {
            Os.poll(pollFds, -1);
        }
        for (int i = pollFds.length -1 ; i >= 0; i--) {
            if ((pollFds[i].revents & POLLIN) == 0) {
                continue;
            }
            if (i == 0) {
                ZygoteConnection newPeer = acceptCommandPeer(abiList);
                peers.add(newPeer);
                fds.add(newPeer.getFileDescriptor());
            } else {
                ZygoteConnection connection = peers.get(i);
                final Runnable command = connection.processOneCommand(this);
                return command;
                ......
            }
        }
    }
}

frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java

Runnable processOneCommand(ZygoteServer zygoteServer) {
    ......
    pid = Zygote.forkAndSpecialize(...);
    try {
        if (pid == 0) {
            // in child
            ......
            return handleChildProc(...);
        } else {
            // In the parent
            handleParentProc(...)
            return null;
        }
    }
}

你可能感兴趣的:(Android)