< Back to all hacks

#56 Merged Kill Loop (3 bash -> 1 bash)

Desktop
Problem
3 separate while-true loops for background kills: SystemUI, dormant services, monitor. Each ~1.5 MB RSS.
Solution
Merged into single loop every 5 min. Expanded kill list to 12 packages. -3 MB RAM.
Lesson
Multiple background bash loops add up. Merging them saves both RAM and context-switch overhead.

Context

Over the course of PocketClaw's optimization, three separate background bash loops had accumulated: one killing SystemUI (which respawns in degraded mode), one killing dormant services that Android restarts periodically, and one monitoring resource usage. Each bash process consumes ~1.5 MB RSS, plus overhead from the sleep/wake cycle.

On a 1 GB device where the goal is to squeeze out every megabyte, 4.5 MB for three redundant loops is wasteful. They all do the same thing: periodically kill packages. Merging them into a single loop saves 3 MB and reduces context-switch overhead.

Implementation

Single merged kill loop replacing all three:

# Single merged kill loop — replaces 3 separate loops
(while true; do
  sleep 300  # 5 minutes
  for PKG in \
    com.android.systemui \
    com.android.settings \
    com.android.keychain \
    com.android.externalstorage \
    com.android.defcontainer \
    com.android.location.fused \
    com.motorola.ccc.devicemanagement \
    com.motorola.ccc.ota \
    com.motorola.android.intent.action.quicklaunch \
    com.android.providers.downloads \
    com.android.inputdevices \
    com.android.certinstaller; do
    am force-stop "$PKG" 2>/dev/null
  done
done) &

This runs as a single backgrounded subshell, launched from the boot script.

Verification

# Check only one kill loop is running:
ps aux | grep "sleep 300" | grep -v grep | wc -l
# Expected: 1

# Check RAM savings (compare before/after):
ps aux | grep bash | grep -v grep
# Expected: fewer bash processes than before

# Verify packages are being killed:
# Wait 5 minutes, then check:
adb shell dumpsys meminfo com.android.systemui | grep TOTAL
# Expected: ~5 MB (degraded mode, not full 70 MB)

Gotchas

  • am force-stop from Termux (uid 10001) may fail for some packages due to FORCE_STOP_PACKAGES permission. From ADB shell (uid 2000) it works for all packages
  • SystemUI always respawns in degraded mode (~5 MB vs 70 MB full). Killing it is still worthwhile
  • The 5-minute interval is a balance between RAM savings (more frequent = lower average) and CPU usage (less frequent = fewer wake cycles)
  • Don't add com.google.android.gms to the kill list — it breaks WiFi routing (Hack #24)
  • Don't kill com.termux — cgroup cascade kills the gateway (Hack #57 explains this)

Result

MetricBeforeAfter
Background bash loops31
RAM for kill loops~4.5 MB~1.5 MB
Kill targets712
Kill intervalMixed (1-5 min)Uniform (5 min)