@@ -44,7 +44,8 @@ wait_for_port() {
4444 return 1
4545}
4646
47- # Check if a port is in use (returns 0 if port is in use)
47+ # Check if a port is in use.
48+ # Returns: 0 = in use, 1 = free, 2 = unknown (no probe tool available)
4849check_port_in_use () {
4950 local port=" $1 "
5051 if command -v nc > /dev/null 2>&1 ; then
@@ -53,22 +54,30 @@ check_port_in_use() {
5354 elif command -v ss > /dev/null 2>&1 ; then
5455 ss -tln 2> /dev/null | grep -q " :${port} "
5556 return $?
56- elif netstat -tln 2> /dev/null | grep -q " :${port} " ; then
57- return 0
57+ elif command -v netstat > /dev/null 2>&1 ; then
58+ netstat -tln 2> /dev/null | grep -q " :${port} "
59+ return $?
5860 fi
59- return 1 # no tool available, skip this port
61+ return 2 # no probe tool — cannot determine
6062}
6163
6264# Pick an available random port (returns port on stdout)
6365pick_available_port () {
64- local port attempts=0
66+ local port attempts=0 rv
6567 while [ $attempts -lt 20 ]; do
6668 if command -v shuf > /dev/null 2>&1 ; then
6769 port=$( shuf -i 10000-65000 -n 1)
6870 else
6971 port=$(( (RANDOM % 55000 ) + 10000 ))
7072 fi
71- if ! check_port_in_use " $port " ; then
73+ check_port_in_use " $port " ; rv=$?
74+ if [ $rv -eq 1 ]; then
75+ echo " $port "
76+ return 0
77+ fi
78+ if [ $rv -eq 2 ]; then
79+ # No probe tool — accept the port; bind-time conflicts will surface
80+ # as a server startup error rather than silent flakiness.
7281 echo " $port "
7382 return 0
7483 fi
@@ -270,13 +279,21 @@ if [ $IS_FWTPM_MODE -eq 1 ]; then
270279 rm -f " $BUILD_DIR " /certs/tpm-* -cert.pem " $BUILD_DIR " /certs/tpm-* -cert.csr
271280 rm -f " $BUILD_DIR " /certs/server-* -cert.pem " $BUILD_DIR " /certs/client-* -cert.pem
272281
273- # Clean up any stale PID files from prior crashed runs
282+ # Clean up any stale PID files from prior crashed runs.
283+ # Validate the process is actually fwtpm_server before killing —
284+ # PIDs can be reused, and signalling an unrelated process would
285+ # cause collateral damage.
274286 for stale_pid_file in /tmp/fwtpm_check_* .pid; do
275287 [ -f " $stale_pid_file " ] || continue
276288 stale_pid=" $( cat " $stale_pid_file " 2> /dev/null) "
277289 if [ -n " $stale_pid " ] && kill -0 " $stale_pid " 2> /dev/null; then
278- kill " $stale_pid " 2> /dev/null
279- sleep 0.3
290+ stale_comm=" $( ps -p " $stale_pid " -o comm= 2> /dev/null) "
291+ case " $stale_comm " in
292+ fwtpm_server|* fwtpm_server* )
293+ kill " $stale_pid " 2> /dev/null
294+ sleep 0.3
295+ ;;
296+ esac
280297 fi
281298 rm -f " $stale_pid_file "
282299 done
0 commit comments