Deep Dive: Services in Init
The init process acts as the ultimate parent for all native services in Android. It manages their lifecycles, monitors for crashes, and controls their execution context using features heavily integrated with Linux cgroups and SELinux.
Service Restart Policy
init provides several options to dictate what happens when a service exits or crashes:
- Default (Restart): By default, if a service exits,
initwill automatically restart it. This is used for persistent daemons likesurfaceflingeroraudioserver. oneshot: The service is launched once and never restarted, even if it exits. This is typically used for configuration scripts or firmware loaders.critical: If a critical service crashes more than four times in four minutes, the device will automatically reboot into recovery mode. This is reserved for services whose failure makes the device completely unusable (e.g.,ueventd,servicemanager).
service servicemanager /system/bin/servicemanager
class core
user system
group system readproc
critical
Service Classes
To manage services in bulk, init groups them into "classes". Common classes include:
core: Essential services required for basic system functionality (e.g.,adbd,logd,servicemanager). Started very early in the boot process.main: The bulk of the Android framework native services (e.g.,zygote,surfaceflinger,mediaserver).late_start: Services that are not strictly required for boot and can be delayed to optimize boot time.
class_start and class_stop
The boot sequence defines when these classes of services are launched using the class_start command within an action.
on post-fs-data
# Start core services
class_start core
on boot
# Start main system services
class_start main
Similarly, class_stop can be used to terminate all services in a given class. This is heavily utilized during shutdown or when performing a soft reboot (e.g., adb shell stop uses class_stop main).
Watchdog and Service Supervision
Android employs watchdog mechanisms to ensure services do not hang or deadlock.
Services can be supervised by a parent watchdog service. If a supervised service fails to pet the watchdog within a specific timeframe, the watchdog assumes the service is deadlocked and terminates it, prompting init to restart the service. This ensures the system remains responsive even if a low-level driver or native service freezes.
# You can check the status of all init services using:
adb shell getprop | grep init.svc
# Example output: [init.svc.surfaceflinger]: [running]