Last active
November 4, 2024 08:54
-
-
Save janhicken/2d68dca53f258637b4d726617478808f to your computer and use it in GitHub Desktop.
A Bash script that runs a co-process and waits until any process is accepting connections on a specific local TCP port.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# A script that runs a co-process and waits until any process is accepting connections on a specific local TCP port. | |
# | |
# Upon successfully connecting to that given port, a SIGTERM is sent to the co-process. | |
# No timeout is applied while waiting, however this script can conveniently wrapped in a TIMEOUT(1) call. | |
# | |
# This script requires no external tools and will make use of Linux' /proc file system. | |
if [[ $# -lt 2 ]]; then | |
printf 'Usage: %s PORT COMMAND [ARGS...]\n' "$0" >&2 | |
exit 1 | |
fi | |
port=$1 | |
shift | |
printf -v expected_local_address '%08X:%04X' 0 "$port" | |
coproc "$@" | |
# The COPROC_PID variable will be unset when the corresponding process exits | |
while [[ -n "$COPROC_PID" ]]; do | |
while read -r _ local_address _ connection_state _; do | |
if [[ "$connection_state" == 0A && "$local_address" == "$expected_local_address" ]]; then | |
kill "$COPROC_PID" | |
wait -f "$COPROC_PID" | |
status=$? | |
# Exit code 143 means "terminated by SIGTERM" which is expected here. | |
# Let's return 0 in this case. | |
if [[ "$status" -eq 143 ]]; then | |
status=0 | |
fi | |
break 2 | |
fi | |
done </proc/"$COPROC_PID"/net/tcp | |
sleep 1 | |
done | |
exit "${status:-1}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment