Skip to content

armgit / soju

Public Imported from GitHub
0

Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.

reaper: decide by bottle membership, not process names; count hidden windows

mikey920d2756f73ca1
diff --git a/docs/DIAGNOSIS.md b/docs/DIAGNOSIS.md
index 5077cc29cf8..75503b5cb4c 100644
--- a/docs/DIAGNOSIS.md
+++ b/docs/DIAGNOSIS.md
@@ -269,6 +269,25 @@ Epic 런처가 시작 40초 뒤마다 죽었다. 런처 로그는 정상 상태
`cd /tmp && pwd -P`로 해석한 경로도 함께 받아들이도록 고쳤다. 고친 뒤 Epic 런처를 앱 번들로
띄우고 2분 뒤 확인: 런처·리퍼·wineserver 모두 생존.
+### 재설계 (2026-09-02): 이름이 아니라 소속으로 판단
+
+전체 리뷰에서 리퍼의 판정 기준 세 가지가 모두 게임을 죽일 수 있다는 것이 드러났다.
+
+- 창 탐지가 `kCGWindowListOptionOnScreenOnly`라서 게임을 최소화하거나 Cmd-H로 숨기거나 다른
+ Space로 옮기면 40초 뒤 kill -9였다.
+- "유휴" 판정이 모드별 하드코딩 목록(D2R.exe, 런처 exe)이라, Battle.net에서 Hearthstone을 켜고
+ 런처를 닫거나 Epic 트레이에서 Exit하면 게임이 살아 있어도 `wineserver -k`였다.
+- 킬 패턴에 앵커가 없어 `tail -f D2R.exe.log` 같은 무관한 프로세스도 대상이었고, 다른 보틀의
+ 같은 exe도 구분하지 못했다.
+
+새 기준: 모든 Wine 프로세스(빌트인 서비스 포함)는 자기 wineserver의 소켓 디렉토리
+(`/private/tmp/.wine-UID/server-DEV-INODE/tmpmap-*`)에 파일을 열어 두고 있고, 그 디렉토리 이름은
+프리픽스에서 나온다. `lsof -a -p <후보> +d <디렉토리>`로 이 보틀의 프로세스만 100ms 안에 얻는다
+(Epic 보틀 15개 프로세스, 0.09초). 그 목록에서 서비스 세트와 런처 헬퍼(Agent, EOS 헬퍼,
+GalaxyClientService, steamservice)를 빼고 아무것도 남지 않을 때만 유휴다. 창 탐지는 전체 목록을
+쓰되 Wine이 프로세스마다 두는 1x1 투명 placeholder 창은 세지 않고, 좀비 판정은 3회(60초)로
+늘렸다. exe 이름 매칭은 경로 구분자와 단어 끝에 앵커를 건다.
+
## Epic 로그인 `too_many_sessions`: ncrypt에 영구 키가 없어서 매번 새 기기가 된다 (2026-08-31)
### 증상
diff --git a/scripts/soju-reaper.sh b/scripts/soju-reaper.sh
index 8cffda7adab..df6d104926a 100755
--- a/scripts/soju-reaper.sh
+++ b/scripts/soju-reaper.sh
@@ -1,59 +1,77 @@
#!/usr/bin/env bash
-# soju-reaper: cleans up game processes that outlive their windows.
+# soju-reaper: cleans up game processes that outlive their windows, and shuts a
+# bottle down once nothing but its idle services is left in it.
#
# Why: under Wine, quitting D2R sometimes leaves D2R.exe alive with no window
# (a shutdown thread misses a wakeup). The user sees a dead Dock icon and a
# process holding gigabytes of RAM. This watchdog kills a game process once it
-# has gone windowless for two consecutive checks, and when the bottle is fully
-# idle (no game, no launcher window) it shuts the whole prefix down so nothing
-# lingers after "quit".
+# has gone windowless for three consecutive checks, and when the bottle is
+# fully idle it shuts the whole prefix down so nothing lingers after "quit".
#
-# Window detection uses CGWindowListCopyWindowInfo via python3+ctypes: no
-# Accessibility permission needed, nothing to install.
+# Which processes belong to this bottle: every Wine process, builtin services
+# included, keeps a shared-memory file open in its wineserver's socket
+# directory (/tmp/.wine-UID/server-DEV-INODE/tmpmap-*), and that directory is
+# named after the prefix. `lsof +d` on it lists exactly this bottle's
+# processes in well under 100 ms, so nothing here matches on process names
+# alone: a `tail -f D2R.exe.log` in Terminal, or the same game running from
+# another bottle, is never touched.
+#
+# "Idle" means: no process in the bottle except the Windows service set and
+# the launcher's own helpers (Agent.exe for Battle.net, EOS helpers for Epic,
+# GalaxyClientService for GOG, steamservice for Steam). A launcher parked in
+# its tray, a game started from a launcher that has since been quit, or a
+# launcher self-update running msiexec all keep the bottle alive.
#
-# Usage: soju-reaper.sh <WINEPREFIX> <wineserver-path> [battlenet|steam|epic]
-# (backgrounded by play.sh / the Battle.net.app launcher)
+# Window detection uses CGWindowListCopyWindowInfo via python3+ctypes: no
+# Accessibility permission needed, nothing to install. A minimized or hidden
+# (Cmd-H) window, or one on another Space, still counts as a window.
#
-# steam mode: closing the Steam window parks it in a tray (as on Windows; the
-# Dock icon brings it back via WINE_DOCK_REOPEN_CMD). Once steam.exe itself has
-# exited, the leftovers (steamservice, winedevice, wineserver) are shut down.
-# epic mode: same tray semantics, keyed on EpicGamesLauncher.exe.
+# Usage: soju-reaper.sh <WINEPREFIX> <wineserver-path> [battlenet|steam|epic|gog]
+# (backgrounded by play.sh / the app bundles)
set -u
-PREFIX="${1:?usage: soju-reaper.sh <WINEPREFIX> <wineserver> [battlenet|steam|epic]}"
+PREFIX="${1:?usage: soju-reaper.sh <WINEPREFIX> <wineserver> [battlenet|steam|epic|gog]}"
WINESERVER="${2:?}"
MODE="${3:-battlenet}"
INTERVAL=20
+ZOMBIE_STRIKES=3 # windowless checks before a game process is killed (60 s)
SWEEP="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/soju-sweep.sh"
+
+# Basenames are matched against the first argv word of a Wine process
+# ("C:\...\D2R.exe -launch ..."), anchored on the path separator and the end of
+# that word, so "D2R.exe.log" or "steam.exe.bak" do not match.
+exe_re(){ local alt="$1"; printf '(^|[\\/])(%s)( |$)' "$alt"; }
+
+# Idle Windows service set (also what soju-sweep removes once no server is up).
+SERVICE_RE="$(exe_re 'services\.exe|winedevice\.exe|plugplay\.exe|rpcss\.exe|svchost\.exe|explorer\.exe|conhost\.exe|tabtip\.exe|wineboot\.exe|winedbg\.exe|start\.exe|control\.exe')"
+
case "$MODE" in
steam)
- GAME_RE='Steam\\steamapps\\' # games live under steamapps
- UI_RE='steam\.exe|steamwebhelper'
- TRAY_RE='steam\.exe'; TRAY_KILL_RE="$UI_RE|steamservice\.exe"
+ GAME_RE='' # games keep their windows on wine-stable
+ HELPER_RE="$(exe_re 'steamservice\.exe|steamwebhelper\.exe|steamwebhelper_real\.exe|steamerrorreporter\.exe|steamerrorreporter64\.exe')"
;;
epic)
- GAME_RE='__none__'
- UI_RE='EpicGamesLauncher\.exe|EpicWebHelper\.exe|EpicOnlineServices'
- TRAY_RE='EpicGamesLauncher\.exe'; TRAY_KILL_RE="$UI_RE"
+ GAME_RE=''
+ HELPER_RE="$(exe_re 'EpicOnlineServicesUserHelper\.exe|EpicOnlineServicesHost\.exe|EpicOnlineServicesUIHelper\.exe|EpicOnlineServicesInstallHelper\.exe|EOSOverlayRenderer-Win64-Shipping\.exe|EOSOverlayRenderer-Win32-Shipping\.exe|EpicWebHelper\.exe|CrashReportClient\.exe')"
;;
gog)
- GAME_RE='__none__'
- UI_RE='GalaxyClient\.exe|QtWebEngineProcess\.exe|GalaxyClientService\.exe|GOG Galaxy Notifications|GalaxyCommunication'
- TRAY_RE='GalaxyClient\.exe'; TRAY_KILL_RE="$UI_RE"
+ GAME_RE=''
+ HELPER_RE="$(exe_re 'GalaxyClientService\.exe|GalaxyCommunication\.exe|GalaxyClientHelper\.exe|GOG Galaxy Notifications Renderer\.exe|QtWebEngineProcess\.exe|GalaxyClient Helper\.exe')"
;;
*)
- GAME_RE='D2R\.exe|BlizzardError\.exe'
- UI_RE='Battle\.net\.exe.*--from-launcher|Battle\.net Launcher\.exe'
+ GAME_RE="$(exe_re 'D2R\.exe')"
+ HELPER_RE="$(exe_re 'Agent\.exe|Battle\.net Helper\.exe|Battle\.net Update Agent\.exe|BlizzardError\.exe|SystemSurvey\.exe')"
;;
esac
# The wineserver for this prefix: wine names its socket directory after the
# prefix's device and inode, and the server runs with that directory as its
-# working directory. If the server is gone while the launcher is still up, the
-# launcher is an orphan: every call that needs the server (closing a handle, for
-# one) blocks forever, so its window stops repainting and stops responding while
-# the process still looks alive. Nothing can rescue it at that point, and the
-# leftovers have to be killed for the next start to work.
+# working directory. If the server is gone while the launcher is still up, the
+# launcher is an orphan: every call that needs the server (closing a handle,
+# for one) blocks forever, so its window stops repainting and stops responding
+# while the process still looks alive. Nothing can rescue it at that point, and
+# the leftovers have to be killed for the next start to work.
+#
# lsof reports the resolved path, and on macOS /tmp is a symlink to
# /private/tmp, so compare against the resolved form as well: with only the
# /tmp spelling the check never matched, and the reaper killed every launcher
@@ -69,110 +87,152 @@ server_alive() {
lsof -a -p "$pids" -d cwd -Fn 2>/dev/null | grep -qxF -e "n$SERVER_DIR" -e "n$SERVER_DIR_REAL"
}
+# PIDs of this bottle's Wine processes (the server itself excluded): every one
+# of them holds a file open in the server directory.
+bottle_pids() {
+ local cand
+ [ -n "$SERVER_DIR" ] || return 0
+ cand=$(pgrep -f '\.exe' 2>/dev/null | tr '\n' ',' | sed 's/,$//')
+ [ -n "$cand" ] || return 0
+ lsof -a -p "$cand" +d "$SERVER_DIR_REAL" -Fp 2>/dev/null | sed -n 's/^p//p' | sort -un
+}
+
+# First argv word of a process, i.e. its Windows exe path.
+exe_of() { ps -o args= -p "$1" 2>/dev/null | sed 's/ -.*//; s/ \/.*//'; }
+
+# Split a pid list into what keeps the bottle alive and what does not.
+classify() { # sets ALIVE_PIDS, GAME_PIDS
+ local pid exe
+ ALIVE_PIDS=""; GAME_PIDS=""
+ for pid in $1; do
+ exe=$(ps -o args= -p "$pid" 2>/dev/null) || continue
+ [[ "$exe" =~ $SERVICE_RE ]] && continue
+ [[ "$exe" =~ $HELPER_RE ]] && continue
+ ALIVE_PIDS="$ALIVE_PIDS $pid"
+ [ -n "$GAME_RE" ] && [[ "$exe" =~ $GAME_RE ]] && GAME_PIDS="$GAME_PIDS $pid"
+ done
+}
+
reap_orphans() {
+ local pids
echo "soju-reaper: the wineserver for $PREFIX is gone, cleaning up its leftovers"
- pkill -9 -f "${TRAY_KILL_RE:-$UI_RE}" 2>/dev/null || true
- [ "$GAME_RE" != "__none__" ] && pkill -9 -f "$GAME_RE" 2>/dev/null || true
+ # Without a server the tmpmap files are gone too, so attribution by server
+ # directory no longer works: fall back to the launcher/helper/game names of
+ # this mode, and let the sweep take the service set.
+ pids=$(pgrep -f "$HELPER_RE" 2>/dev/null || true)
+ [ -n "$GAME_RE" ] && pids="$pids $(pgrep -f "$GAME_RE" 2>/dev/null || true)"
+ case "$MODE" in
+ steam) pids="$pids $(pgrep -f "$(exe_re 'steam\.exe')" 2>/dev/null || true)" ;;
+ epic) pids="$pids $(pgrep -f "$(exe_re 'EpicGamesLauncher\.exe')" 2>/dev/null || true)" ;;
+ gog) pids="$pids $(pgrep -f "$(exe_re 'GalaxyClient\.exe')" 2>/dev/null || true)" ;;
+ *) pids="$pids $(pgrep -f "$(exe_re 'Battle\.net\.exe|Battle\.net Launcher\.exe')" 2>/dev/null || true)" ;;
+ esac
+ # shellcheck disable=SC2086
+ [ -n "${pids// /}" ] && kill -9 $pids 2>/dev/null || true
sleep 2; [ -x "$SWEEP" ] && "$SWEEP" >/dev/null 2>&1
}
+# PIDs that own at least one real window: on-screen, or off-screen but a
+# normal-layer window with a size (minimized, hidden, on another Space). Wine
+# keeps 1x1 fully transparent placeholder windows for every process, which do
+# not count. Prints nothing (and the caller skips the round) if the query fails.
window_pids() {
/usr/bin/python3 - <<'PY'
-import ctypes
-cg = ctypes.CDLL("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics")
-cf = ctypes.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
-cg.CGWindowListCopyWindowInfo.restype = ctypes.c_void_p
-cg.CGWindowListCopyWindowInfo.argtypes = [ctypes.c_uint32, ctypes.c_uint32]
-cf.CFArrayGetCount.restype = ctypes.c_long
-cf.CFArrayGetCount.argtypes = [ctypes.c_void_p]
-cf.CFArrayGetValueAtIndex.restype = ctypes.c_void_p
-cf.CFArrayGetValueAtIndex.argtypes = [ctypes.c_void_p, ctypes.c_long]
-cf.CFDictionaryGetValue.restype = ctypes.c_void_p
-cf.CFDictionaryGetValue.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
-cf.CFStringCreateWithCString.restype = ctypes.c_void_p
-cf.CFStringCreateWithCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32]
-cf.CFNumberGetValue.restype = ctypes.c_bool
-cf.CFNumberGetValue.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p]
-key = cf.CFStringCreateWithCString(None, b"kCGWindowOwnerPID", 0x08000100)
-arr = cg.CGWindowListCopyWindowInfo(1, 0) # kCGWindowListOptionOnScreenOnly
-pids = set()
-for i in range(cf.CFArrayGetCount(arr)):
- num = cf.CFDictionaryGetValue(cf.CFArrayGetValueAtIndex(arr, i), key)
- if num:
- v = ctypes.c_int(0)
- if cf.CFNumberGetValue(num, 9, ctypes.byref(v)):
- pids.add(v.value)
-print(" ".join(map(str, sorted(pids))))
+import ctypes, sys
+try:
+ cg = ctypes.CDLL("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics")
+ cf = ctypes.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
+ cg.CGWindowListCopyWindowInfo.restype = ctypes.c_void_p
+ cg.CGWindowListCopyWindowInfo.argtypes = [ctypes.c_uint32, ctypes.c_uint32]
+ cf.CFArrayGetCount.restype = ctypes.c_long
+ cf.CFArrayGetCount.argtypes = [ctypes.c_void_p]
+ cf.CFArrayGetValueAtIndex.restype = ctypes.c_void_p
+ cf.CFArrayGetValueAtIndex.argtypes = [ctypes.c_void_p, ctypes.c_long]
+ cf.CFDictionaryGetValue.restype = ctypes.c_void_p
+ cf.CFDictionaryGetValue.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
+ cf.CFStringCreateWithCString.restype = ctypes.c_void_p
+ cf.CFStringCreateWithCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32]
+ cf.CFNumberGetValue.restype = ctypes.c_bool
+ cf.CFNumberGetValue.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p]
+ cf.CFBooleanGetValue.restype = ctypes.c_bool
+ cf.CFBooleanGetValue.argtypes = [ctypes.c_void_p]
+ def key(s): return cf.CFStringCreateWithCString(None, s, 0x08000100)
+ kPID, kLayer, kAlpha, kOn, kBounds = key(b"kCGWindowOwnerPID"), key(b"kCGWindowLayer"), key(b"kCGWindowAlpha"), key(b"kCGWindowIsOnscreen"), key(b"kCGWindowBounds")
+ kW, kH = key(b"Width"), key(b"Height")
+ def num(d, k, kind=9, ctype=ctypes.c_int):
+ n = cf.CFDictionaryGetValue(d, k)
+ if not n: return None
+ v = ctype(0)
+ return v.value if cf.CFNumberGetValue(n, kind, ctypes.byref(v)) else None
+ arr = cg.CGWindowListCopyWindowInfo(0, 0) # kCGWindowListOptionAll
+ pids = set()
+ for i in range(cf.CFArrayGetCount(arr)):
+ w = cf.CFArrayGetValueAtIndex(arr, i)
+ pid = num(w, kPID)
+ if pid is None: continue
+ on = cf.CFDictionaryGetValue(w, kOn)
+ if on and cf.CFBooleanGetValue(on):
+ pids.add(pid); continue
+ if num(w, kLayer) != 0: continue
+ alpha = num(w, kAlpha, 13, ctypes.c_double)
+ if alpha is not None and alpha <= 0: continue
+ b = cf.CFDictionaryGetValue(w, kBounds)
+ if not b: continue
+ wd, ht = num(b, kW, 13, ctypes.c_double), num(b, kH, 13, ctypes.c_double)
+ if wd is None or ht is None or wd <= 1 or ht <= 1: continue
+ pids.add(pid)
+ print(" ".join(map(str, sorted(pids))))
+except Exception:
+ sys.exit(1)
PY
}
-declare -A STRIKES
+declare -a STRIKES # indexed by pid
IDLE_STRIKES=0
ORPHAN_STRIKES=0
-if [ "$MODE" = "steam" ] || [ "$MODE" = "epic" ] || [ "$MODE" = "gog" ]; then
- # Steam parks itself in an (invisible on macOS) tray when its window is closed,
- # so a missing window means nothing here. Only once steam.exe has really gone
- # (Steam menu > Exit) do we shut the rest of the bottle down.
- while true; do
- sleep "$INTERVAL"
- if ! server_alive; then
- ORPHAN_STRIKES=$((ORPHAN_STRIKES + 1))
- if [ "$ORPHAN_STRIKES" -ge 2 ]; then reap_orphans; exit 0; fi
- else
- ORPHAN_STRIKES=0
- fi
- if ! pgrep -f "$TRAY_RE" >/dev/null 2>&1; then
- IDLE_STRIKES=$((IDLE_STRIKES + 1))
- if [ "$IDLE_STRIKES" -ge 2 ]; then
- WINEPREFIX="$PREFIX" "$WINESERVER" -k 2>/dev/null || true
- sleep 3; [ -x "$SWEEP" ] && "$SWEEP" >/dev/null 2>&1
- sleep 3
- pkill -9 -f "$TRAY_KILL_RE" 2>/dev/null || true
- exit 0
- fi
- else
- IDLE_STRIKES=0
- fi
- done
-fi
-
while true; do
sleep "$INTERVAL"
if ! server_alive; then
ORPHAN_STRIKES=$((ORPHAN_STRIKES + 1))
if [ "$ORPHAN_STRIKES" -ge 2 ]; then reap_orphans; exit 0; fi
- else
- ORPHAN_STRIKES=0
+ continue
fi
+ ORPHAN_STRIKES=0
- GAME_PIDS=$(pgrep -f "$GAME_RE" 2>/dev/null || true)
- UI_PIDS=$(pgrep -f "$UI_RE" 2>/dev/null || true)
+ classify "$(bottle_pids)"
- # Bottle fully gone? Nothing left to do.
- if [ -z "$GAME_PIDS" ] && [ -z "$UI_PIDS" ]; then
+ # Nothing but services and helpers left? Two checks in a row and the bottle
+ # comes down (wineserver -k), then the sweep removes the service set.
+ if [ -z "${ALIVE_PIDS// /}" ]; then
IDLE_STRIKES=$((IDLE_STRIKES + 1))
- # Two idle checks in a row: tear down leftover services (Agent, winedevice…)
if [ "$IDLE_STRIKES" -ge 2 ]; then
WINEPREFIX="$PREFIX" "$WINESERVER" -k 2>/dev/null || true
sleep 3; [ -x "$SWEEP" ] && "$SWEEP" >/dev/null 2>&1
+ sleep 3
+ # Helpers do not always notice the server going away.
+ pids=$(pgrep -f "$HELPER_RE" 2>/dev/null || true)
+ # shellcheck disable=SC2086
+ [ -n "$pids" ] && kill -9 $pids 2>/dev/null || true
exit 0
fi
continue
fi
IDLE_STRIKES=0
- [ -z "$GAME_PIDS" ] && continue
- WINS=" $(window_pids) "
-
+ # Zombie games: a game process of this bottle with no window at all for
+ # ZOMBIE_STRIKES checks in a row.
+ [ -n "${GAME_PIDS// /}" ] || continue
+ WINS=" $(window_pids) " || continue
+ [ "$WINS" != " " ] || continue # query failed or no windows anywhere: skip the round
for pid in $GAME_PIDS; do
if [[ "$WINS" == *" $pid "* ]]; then
STRIKES[$pid]=0
else
STRIKES[$pid]=$(( ${STRIKES[$pid]:-0} + 1 ))
- # Windowless on two consecutive checks (>=40s): it's a zombie, reap it.
- if [ "${STRIKES[$pid]}" -ge 2 ]; then
+ if [ "${STRIKES[$pid]}" -ge "$ZOMBIE_STRIKES" ]; then
+ echo "soju-reaper: $(exe_of "$pid") ($pid) has had no window for $((ZOMBIE_STRIKES * INTERVAL)) s, killing it"
kill -9 "$pid" 2>/dev/null || true
unset "STRIKES[$pid]"
fi