Android启动流程(五)——init进程对子进程的监控
init进程会读取rc文件,然后孵化很多其他系统服务进程,为防止子进程死亡后称为僵尸进程,init需要监测子进程是否死亡,如果死亡,则清除子进程资源,并重新拉起进程。
system/core/init/init.cpp
InstallSignalFdHandler(&epoll);
init进程第二阶段启动的时候,创建了epoll,并将子进程相关处理注册到epoll中
static void InstallSignalFdHandler(Epoll* epoll) {// Applying SA_NOCLDSTOP to a defaulted SIGCHLD handler prevents the signalfd from receiving// SIGCHLD when a child process stops or continues (b/77867680#comment9).const struct sigaction act { .sa_handler = SIG_DFL, .sa_flags = SA_NOCLDSTOP };sigaction(SIGCHLD, &act, nullptr);sigset_t mask;sigemptyset(&mask);sigaddset(&mask, SIGCHLD);if (!IsRebootCapable()) {// If init does not have the CAP_SYS_BOOT capability, it is running in a container.// In that case, receiving SIGTERM will cause the system to shut down.sigaddset(&mask, SIGTERM);}if (sigprocmask(SIG_BLOCK, &mask, nullptr) == -1) {PLOG(FATAL) << "failed to block signals";}// Register a handler to unblock signals in the child processes.const int result = pthread_atfork(nullptr, nullptr, &UnblockSignals);if (result != 0) {LOG(FATAL) << "Failed to register a fork handler: " << strerror(result);}signal_fd = signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);if (signal_fd == -1) {PLOG(FATAL) << "failed to create signalfd";}constexpr int flags = EPOLLIN | EPOLLPRI;auto handler = std::bind(HandleSignalFd, false);if (auto result = epoll->RegisterHandler(signal_fd, handler, flags); !result.ok()) {LOG(FATAL) << result.error();}
}
使用epoll注册监听信号量fd,子进程死亡会发送信号给init进程,这里就会调用epoll中注册的回调函数HandleSignalFd
static void HandleSignalFd(bool one_off) {signalfd_siginfo siginfo;auto started = std::chrono::steady_clock::now();do {ssize_t bytes_read = TEMP_FAILURE_RETRY(read(signal_fd, &siginfo, sizeof(siginfo)));if (bytes_read < 0 && errno == EAGAIN) {auto now = std::chrono::steady_clock::now();std::chrono::duration<double> waited = now - started;if (waited >= kDiagnosticTimeout) {LOG(ERROR) << "epoll() woke us up, but we waited with no SIGCHLD!";started = now;}std::this_thread::sleep_for(100ms);continue;}if (bytes_read != sizeof(siginfo)) {PLOG(ERROR) << "Failed to read siginfo from signal_fd";return;}break;} while (!one_off);switch (siginfo.ssi_signo) {case SIGCHLD:ReapAnyOutstandingChildren();break;case SIGTERM:HandleSigtermSignal(siginfo);break;default:PLOG(ERROR) << "signal_fd: received unexpected signal " << siginfo.ssi_signo;break;}
}
对于SIGCHLD信号,调用ReapAnyOutstandingChildren
system/core/init/sigchld_handler.cpp
void ReapAnyOutstandingChildren() {while (ReapOneProcess() != 0) {}}
static pid_t ReapOneProcess() {siginfo_t siginfo = {};// This returns a zombie pid or informs us that there are no zombies left to be reaped.// It does NOT reap the pid; that is done below.if (TEMP_FAILURE_RETRY(waitid(P_ALL, 0, &siginfo, WEXITED | WNOHANG | WNOWAIT)) != 0) {PLOG(ERROR) << "waitid failed";return 0;}auto pid = siginfo.si_pid;if (pid == 0) return 0;// At this point we know we have a zombie pid, so we use this scopeguard to reap the pid// whenever the function returns from this point forward.// We do NOT want to reap the zombie earlier as in Service::Reap(), we kill(-pid, ...) and we// want the pid to remain valid throughout that (and potentially future) usages.auto reaper = make_scope_guard([pid] { TEMP_FAILURE_RETRY(waitpid(pid, nullptr, WNOHANG)); });std::string name;std::string wait_string;Service* service = nullptr;if (SubcontextChildReap(pid)) {name = "Subcontext";} else {//查找死亡进程pidservice = ServiceList::GetInstance().FindService(pid, &Service::pid);if (service) {name = StringPrintf("Service '%s' (pid %d)", service->name().c_str(), pid);if (service->flags() & SVC_EXEC) {auto exec_duration = boot_clock::now() - service->time_started();auto exec_duration_ms =std::chrono::duration_cast<std::chrono::milliseconds>(exec_duration).count();wait_string = StringPrintf(" waiting took %f seconds", exec_duration_ms / 1000.0f);} else if (service->flags() & SVC_ONESHOT) {auto exec_duration = boot_clock::now() - service->time_started();auto exec_duration_ms =std::chrono::duration_cast<std::chrono::milliseconds>(exec_duration).count();wait_string = StringPrintf(" oneshot service took %f seconds in background",exec_duration_ms / 1000.0f);}} else {name = StringPrintf("Untracked pid %d", pid);}}if (siginfo.si_code == CLD_EXITED) {LOG(INFO) << name << " exited with status " << siginfo.si_status << wait_string;} else {LOG(INFO) << name << " received signal " << siginfo.si_status << wait_string;}if (!service) {LOG(INFO) << name << " did not have an associated service entry and will not be reaped";return pid;}//杀死进程,清除资源,并设置重启标志service->Reap(siginfo);if (service->flags() & SVC_TEMPORARY) {ServiceList::GetInstance().RemoveService(*service);}return pid;
}
调用Reap函数清理子进程
system/core/init/service.cpp
void Service::Reap(const siginfo_t& siginfo) {//杀死进程if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {KillProcessGroup(SIGKILL, false);} else {// Legacy behavior from ~2007 until Android R: this else branch did not exist and we did not// kill the process group in this case.if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {// The new behavior in Android R is to kill these process groups in all cases. The// 'true' parameter instructions KillProcessGroup() to report a warning message where it// detects a difference in behavior has occurred.KillProcessGroup(SIGKILL, true);}}// Remove any socket resources we may have created.//清除socket节点for (const auto& socket : sockets_) {if (socket.persist) {continue;}auto path = ANDROID_SOCKET_DIR "/" + socket.name;unlink(path.c_str());}for (const auto& f : reap_callbacks_) {f(siginfo);}if ((siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) && on_failure_reboot_target_) {LOG(ERROR) << "Service with 'reboot_on_failure' option failed, shutting down system.";trigger_shutdown(*on_failure_reboot_target_);}if (flags_ & SVC_EXEC) UnSetExec();if (name_ == "zygote" || name_ == "zygote64") {//如果是zygote,则清除所有服务进程removeAllEmptyProcessGroups();}if (flags_ & SVC_TEMPORARY) return;pid_ = 0;flags_ &= (~SVC_RUNNING);start_order_ = 0;// Oneshot processes go into the disabled state on exit,// except when manually restarted.if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART) && !(flags_ & SVC_RESET)) {flags_ |= SVC_DISABLED;}// Disabled and reset processes do not get restarted automatically.if (flags_ & (SVC_DISABLED | SVC_RESET)) {NotifyStateChange("stopped");return;}#if INIT_FULL_SOURCESstatic bool is_apex_updatable = android::sysprop::ApexProperties::updatable().value_or(false);
#elsestatic bool is_apex_updatable = false;
#endifconst bool is_process_updatable = !use_bootstrap_ns_ && is_apex_updatable;// If we crash > 4 times in 'fatal_crash_window_' minutes or before boot_completed,// reboot into bootloader or set crashing propertyboot_clock::time_point now = boot_clock::now();if (((flags_ & SVC_CRITICAL) || is_process_updatable) && !(flags_ & SVC_RESTART)) {bool boot_completed = GetBoolProperty("sys.boot_completed", false);if (now < time_crashed_ + fatal_crash_window_ || !boot_completed) {if (++crash_count_ > 4) {auto exit_reason = boot_completed ?"in " + std::to_string(fatal_crash_window_.count()) + " minutes" :"before boot completed";if (flags_ & SVC_CRITICAL) {if (!GetBoolProperty("init.svc_debug.no_fatal." + name_, false)) {// Aborts into `fatal_reboot_target_'.SetFatalRebootTarget(fatal_reboot_target_);LOG(FATAL) << "critical process '" << name_ << "' exited 4 times "<< exit_reason;}} else {LOG(ERROR) << "process with updatable components '" << name_<< "' exited 4 times " << exit_reason;// Notifies update_verifier and apexdSetProperty("sys.init.updatable_crashing_process_name", name_);SetProperty("sys.init.updatable_crashing", "1");}}} else {time_crashed_ = now;crash_count_ = 1;}}flags_ &= (~SVC_RESTART);//设置重启标志位flags_ |= SVC_RESTARTING;// Execute all onrestart commands for this service.//启动所有rc中标志位onrestart的服务onrestart_.ExecuteAllCommands();NotifyStateChange("restarting");return;
}
这里清除了进程的资源,并设置该进程标志为SVC_RESTARTING,并启动rc中定义的onrestart相关服务
while (true) {...if (!IsShuttingDown()) {auto next_process_action_time = HandleProcessActions();// If there's a process that needs restarting, wake up in time for that.if (next_process_action_time) {epoll_timeout = std::chrono::ceil<std::chrono::milliseconds>(*next_process_action_time - boot_clock::now());if (*epoll_timeout < 0ms) epoll_timeout = 0ms;}}...}
init进程的死循环中HandleProcessActions会处理服务重启
static std::optional<boot_clock::time_point> HandleProcessActions() {std::optional<boot_clock::time_point> next_process_action_time;//遍历所有的servicefor (const auto& s : ServiceList::GetInstance()) {if ((s->flags() & SVC_RUNNING) && s->timeout_period()) {auto timeout_time = s->time_started() + *s->timeout_period();if (boot_clock::now() > timeout_time) {s->Timeout();} else {if (!next_process_action_time || timeout_time < *next_process_action_time) {next_process_action_time = timeout_time;}}}//如果没有标志为SVC_RESTARTING,则跳过if (!(s->flags() & SVC_RESTARTING)) continue;auto restart_time = s->time_started() + s->restart_period();if (boot_clock::now() > restart_time) {//调用Start重启服务if (auto result = s->Start(); !result.ok()) {LOG(ERROR) << "Could not restart process '" << s->name() << "': " << result.error();}} else {if (!next_process_action_time || restart_time < *next_process_action_time) {next_process_action_time = restart_time;}}}return next_process_action_time;
}
调用Start函数执行
Result<void> Service::Start() {...pid_t pid = -1;if (namespaces_.flags) {pid = clone(nullptr, nullptr, namespaces_.flags | SIGCHLD, nullptr);} else {//新建一个进程pid = fork();}if (pid == 0) {//子进程中执行,运行子进程服务umask(077);RunService(override_mount_namespace, descriptors, std::move(pipefd));_exit(127);}if (pid < 0) {pid_ = 0;return ErrnoError() << "Failed to fork";}...
}
fork子进程,并调用RunService执行service
void Service::RunService(const std::optional<MountNamespace>& override_mount_namespace,const std::vector<Descriptor>& descriptors,std::unique_ptr<std::array<int, 2>, decltype(&ClosePipe)> pipefd) {...if (!ExpandArgsAndExecv(args_, sigstop_)) {PLOG(ERROR) << "cannot execv('" << args_[0]<< "'). See the 'Debugging init' section of init's README.md for tips";}
}
调用ExpandArgsAndExecv执行
static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {std::vector<std::string> expanded_args;std::vector<char*> c_strings;expanded_args.resize(args.size());c_strings.push_back(const_cast<char*>(args[0].data()));for (std::size_t i = 1; i < args.size(); ++i) {auto expanded_arg = ExpandProps(args[i]);if (!expanded_arg.ok()) {LOG(FATAL) << args[0] << ": cannot expand arguments': " << expanded_arg.error();}expanded_args[i] = *expanded_arg;c_strings.push_back(expanded_args[i].data());}c_strings.push_back(nullptr);if (sigstop) {kill(getpid(), SIGSTOP);}return execv(c_strings[0], c_strings.data()) == 0;
}
调用execv执行可执行文件
相关文章:
Android启动流程(五)——init进程对子进程的监控
init进程会读取rc文件,然后孵化很多其他系统服务进程,为防止子进程死亡后称为僵尸进程,init需要监测子进程是否死亡,如果死亡,则清除子进程资源,并重新拉起进程。 system/core/init/init.cpp InstallSigna…...

Python每日一练:蚂蚁家族(详解集合法)
文章目录 前言一、题目二、代码分析总结 前言 这题挺有意思,感觉评简单难度有点低了,如果正经用无向图来做,代码还是有点长的。首先得建立节点,估计除第一个和最后一个每个节点都是一条线连进,一条线连出的。就可以这…...

图神经网络:在KarateClub数据集上动手实现图神经网络
文章说明: 1)参考资料:PYG官方文档。超链。 2)博主水平不高,如有错误还望批评指正。 3)我在百度网盘上传了这篇文章的jupyter notebook。超链。提取码8888。 文章目录 文献阅读:代码实操: 文献阅读: 参考文…...
ArduPilot之开源代码调试技巧
ArduPilot之开源代码调试技巧 1. 源由2. ArduPilot Code Debugging Part13. ArduPilot Code Debugging Part24. 持续更新中。。。5. 参考资料 1. 源由 对于如何调试和验证ArduPilot,对于新手来说,有的时候反而是入门的一个门槛。 其实这个并不难&#…...

Linux网络基础-2
在之前的网络基础博客中,我们对网络的基本概念进行了一个简单的介绍,那么接下来的网络内容中,我们将对网络通信中的典型协议进行详细解释。 我们根据网络协议中的分层来对典型协议进行注意介绍,不过对于物理层的传输我们不做考究…...
软件测试报告模板
目录 2 1 概述... 3 1.1 测试目的... 3 1.2 测试策略... 3 1.3 测试方法... 3 1.4 计划验收标准... 3 1.5 测试用例... 4...

记一次azkaban调度异常处理
一、背景 预发布环境使用的数据库性能比较低,根据业务测试的需求,需要将数据库更换成 稳定高性能的数据库。更换业务数据库后azkaban定时任务失败 二、数据库服务信息 说明:该部分使用代号来代替,非真实信息 该数据库存储了azka…...
开发一个vue自定义指令的npm库-系列三:使用rollup打包npm库并发布
配置 rollup 使用rollup将 TypeScript 代码转换为 JavaScript,然后进行压缩和输出到目标文件。 项目根目录新建rollup.config.js import typescript from "rollup/plugin-typescript"; import terser from "rollup/plugin-terser"; import de…...

C嘎嘎的运算符重载基础教程以及遵守规则【文末赠书三本】
博主名字:阿玥的小东东 大家一起共进步! 目录 基础概念 优先级和结合性 不会改变用法 在全局范围内重载运算符 小结 本期送书:盼了一年的Core Java最新版卷Ⅱ,终于上市了 基础概念 运算符重载是通过函数重载实现的…...

【MCAL_UART】-1.2-图文详解RS232,RS485和MODBUS的关系
目录 1 UART,RS232和RS485通信拓扑 2 什么是RS232 2.1 RS232标准的演变 2.2 RS232标准讲了哪些 2.2.1 RS232通信的电平 2.2.2 RS232通信的带宽 2.2.3 RS232通信距离 2.2.4 RS232通信的机械接口 3 什么是RS485 3.1 RS485标准的演变 3.2 RS485标准讲了哪些…...
设计模式详解(二)——单例模式
单例模式简介 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,创建型模式是一类最常用的设计模式,在软件开发中应用非常广泛,它提供了一种创建对象的最佳方式。 单例模…...

为什么hooks不能在循环、条件或嵌套函数中调用
hooks不能在循环、条件或嵌套函数中调用 为什么? 带着疑问一起去看源码吧~ function App() {const [num, setNum] useState(0);const [count, setCount] useState(0);const handleClick () > {setNum(num > num 1)setCount(2)}return <p …...

互联网赚钱项目有哪些?目前最火的互联网项目
互联网是一个神奇的行业,大门不出二门不迈,一根网线一台电脑,甚至一台手机就可以赚钱。它给我们创造了前所未有的商业机会,让成千上万有梦想,敢想敢干的人通过互联网获得了巨大的成功!正因为如此࿰…...

队列、栈专题
队列、栈专题 LeetCode 20. 有效的括号解题思路代码实现 LeetCode 921. 使括号有效的最少添加解题思路代码实现 LeetCode 1541. 平衡括号字符串的最少插入次数解题思路代码实现 总结 不要纠结,干就完事了,熟练度很重要!!ÿ…...

TensorFlow vs PyTorch:哪一个更适合您的深度学习项目?
在深度学习领域中,TensorFlow 和 PyTorch 都是非常流行的框架。这两个框架都提供了用于开发神经网络模型的工具和库,但它们在设计和实现上有很大的差异。在本文中,我们将比较 TensorFlow 和 PyTorch,并讨论哪个框架更适合您的深度…...
大项目环境配置
目录 Linux的龙蜥8是什么? OpenGL是什么? 能讲讲qt是什么吗? 我可以把qt技术理解为c工程师的前端开发手段吗? 我其实一直有些不懂大家所说的这个开发框架啥的,这个该如何理解呢 那现在在我看来,框架意…...
Elasticsearch——》正则regexp
推荐链接: 总结——》【Java】 总结——》【Mysql】 总结——》【Redis】 总结——》【Kafka】 总结——》【Spring】 总结——》【SpringBoot】 总结——》【MyBatis、MyBatis-Plus】 总结——》【Linux】 总结——》【MongoD…...

五面阿里Java岗,从小公司到阿里的面经总结
面试 笔试常见的问题 面试常见的问题下面给的面试题基本都有。 1 手写代码:手写代码一般会考单例、排序、线程、消费者生产者 排序。 2 写SQL很常考察group by、内连接和外连接 2.面试1-5面总结 1)让你自我介绍 2)做两道算法…...

redis(7)
全局ID生成器: 全局ID生成器,是一种在分布式系统下用来生成全局唯一ID的工具,一般要满足以下特性 唯一性高可用(随时访问随时生成)递增性安全性(不能具有规律性)高性能(生成ID的速度快) 为了增加ID的安全性,我们不会使用redis自增的数值&am…...
互联网从业者高频单词 300个
测试 (Test) 软件 (Software) 用例 (Test Case) 缺陷 (Defect) 提交 (Submit) 回归测试 (Regression Testing) 验收测试 (Acceptance Testing) 单元测试 (Unit Testing) 集成测试 (Integration Testing) 性能测试 (Performance Testing) 负载测试 (load Testing) 压…...

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型
摘要 拍照搜题系统采用“三层管道(多模态 OCR → 语义检索 → 答案渲染)、两级检索(倒排 BM25 向量 HNSW)并以大语言模型兜底”的整体框架: 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后,分别用…...

深入浅出Asp.Net Core MVC应用开发系列-AspNetCore中的日志记录
ASP.NET Core 是一个跨平台的开源框架,用于在 Windows、macOS 或 Linux 上生成基于云的新式 Web 应用。 ASP.NET Core 中的日志记录 .NET 通过 ILogger API 支持高性能结构化日志记录,以帮助监视应用程序行为和诊断问题。 可以通过配置不同的记录提供程…...

iOS 26 携众系统重磅更新,但“苹果智能”仍与国行无缘
美国西海岸的夏天,再次被苹果点燃。一年一度的全球开发者大会 WWDC25 如期而至,这不仅是开发者的盛宴,更是全球数亿苹果用户翘首以盼的科技春晚。今年,苹果依旧为我们带来了全家桶式的系统更新,包括 iOS 26、iPadOS 26…...
日语学习-日语知识点小记-构建基础-JLPT-N4阶段(33):にする
日语学习-日语知识点小记-构建基础-JLPT-N4阶段(33):にする 1、前言(1)情况说明(2)工程师的信仰2、知识点(1) にする1,接续:名词+にする2,接续:疑问词+にする3,(A)は(B)にする。(2)復習:(1)复习句子(2)ために & ように(3)そう(4)にする3、…...

visual studio 2022更改主题为深色
visual studio 2022更改主题为深色 点击visual studio 上方的 工具-> 选项 在选项窗口中,选择 环境 -> 常规 ,将其中的颜色主题改成深色 点击确定,更改完成...

聊聊 Pulsar:Producer 源码解析
一、前言 Apache Pulsar 是一个企业级的开源分布式消息传递平台,以其高性能、可扩展性和存储计算分离架构在消息队列和流处理领域独树一帜。在 Pulsar 的核心架构中,Producer(生产者) 是连接客户端应用与消息队列的第一步。生产者…...
多模态商品数据接口:融合图像、语音与文字的下一代商品详情体验
一、多模态商品数据接口的技术架构 (一)多模态数据融合引擎 跨模态语义对齐 通过Transformer架构实现图像、语音、文字的语义关联。例如,当用户上传一张“蓝色连衣裙”的图片时,接口可自动提取图像中的颜色(RGB值&…...
基础测试工具使用经验
背景 vtune,perf, nsight system等基础测试工具,都是用过的,但是没有记录,都逐渐忘了。所以写这篇博客总结记录一下,只要以后发现新的用法,就记得来编辑补充一下 perf 比较基础的用法: 先改这…...

React19源码系列之 事件插件系统
事件类别 事件类型 定义 文档 Event Event 接口表示在 EventTarget 上出现的事件。 Event - Web API | MDN UIEvent UIEvent 接口表示简单的用户界面事件。 UIEvent - Web API | MDN KeyboardEvent KeyboardEvent 对象描述了用户与键盘的交互。 KeyboardEvent - Web…...

【2025年】解决Burpsuite抓不到https包的问题
环境:windows11 burpsuite:2025.5 在抓取https网站时,burpsuite抓取不到https数据包,只显示: 解决该问题只需如下三个步骤: 1、浏览器中访问 http://burp 2、下载 CA certificate 证书 3、在设置--隐私与安全--…...