From c9df7be964e5d9fc9cb87e7c60964cd6b3799619 Mon Sep 17 00:00:00 2001
From: Aquila Macedo <aquilamacedo@riseup.net>
Date: Thu, 30 Oct 2025 16:36:20 -0300
Subject: [PATCH] Fix autopkgtest helper when memcached is already running

Start memcached only if port 11211 is free and add a short delay after
starting it to avoid races.

Also guard the cleanup so we only kill the memcached process when we
actually started it, fixing the autopkgtest failure caused by "kill: No
such process".
---
 debian/start_memcached_and_run.sh | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/debian/start_memcached_and_run.sh b/debian/start_memcached_and_run.sh
index 953852c..2355c1d 100755
--- a/debian/start_memcached_and_run.sh
+++ b/debian/start_memcached_and_run.sh
@@ -6,15 +6,22 @@
 set -e
 
 MEMCACHED_USER=nobody
+MEMCACHED_PORT=11211
 
-# Start memcached
-/usr/bin/memcached -u ${MEMCACHED_USER} &
-PID=$!
+# start memcached only if nothing is listening on MEMCACHED_PORT
+if ! ss -ltnp "sport = :${MEMCACHED_PORT}" 2>/dev/null | grep -q memcached; then
+  /usr/bin/memcached -u "$MEMCACHED_USER" -p "$MEMCACHED_PORT" 2>/dev/null &
+  PID=$!
+  # small delay to avoid race (ensure daemon is ready)
+  sleep 2
+fi
 
 "$@"
 
 cleanup() {
-	# Stop memcached
-	kill -9 $PID
+  # Stop memcached
+  if [ -n "$PID" ]; then
+    kill -0 "$PID" 2>/dev/null && kill -9 "$PID" 2>/dev/null || true
+  fi
 }
 trap cleanup EXIT INT TERM ALRM
-- 
2.47.2

