Updates on 2022/1/17

My Mac keeps having increasingly frequent issues where the corespotlightd process starts consuming all the memory on the system, logging me out of iCloud and freezing up the entire machine to where I can't even reboot.

Since I don't want to debug a macOS built-in process, and I can't turn it off in settings, it seems like the only reasonable solution is to continually monitor the resident memory usage of the process and kill it if it starts consuming too much, so I wrote up a little bash script to do just that.

  1. We need to ensure there's only one copy of this script running on the system at any given time. So I use a lockfile in /tmp.
  2. We filter ps aux to get the PID of corespotlightd, and if it's running, get the resident set (real memory usage, more or less) size.
  3. If it's using more memory than $MAXRSS (1GB for now), kill -9 it, and repeat every 30 seconds.
#!/bin/bash

LOCKFILE=/tmp/limit_corespotlightd.lock
if [ -f "$LOCKFILE" ]; then
    exit
else
    touch "$LOCKFILE"
fi

MAXRSS=1000000 # 1GB

while true; do
    PID=$(ps aux | grep '/corespotlightd$' | awk '{ print $2 }')

    if [ -n "$PID" ]; then
        RSS=$(ps -"$PID" -o rss | grep '[0-9]')

        if [ "$RSS" -gt "$MAXRSS" ]; then
            echo 'corespotlightd is using' "$RSS" 'kB; killing pid' "$PID"
            kill -9 "$PID"
        fi
    fi

    sleep 30
done