bash-com/bind-input

62 lines
1.4 KiB
Plaintext
Raw Normal View History

#!/bin/bash
# (1) Init.
#--------------------------------------------------------#
# (1) Get current absolute dir
ROOT=$(dirname `realpath $0`);
# (2) Check argc
test $# -lt 2 && echo -e "error: too fewarguments\n\n\e[1mUSAGE\e[0m\n\tbind-input <id> <port>\n\n\e[1mARGUMENTS\e[0m\n\t<id>\tThe identifier of the input (buffer name)\n\t<port>\tTo port to listen to\n" && exit 1;
# (3) Check @PORT range #
MIN_PORT=49152;
MAX_PORT=65535;
test "$2" -gt "$MAX_PORT" -o "$2" -lt "$MIN_PORT" && echo "error: <port> must be between $MIN_PORT and $MAX_PORT" && exit 1;
# (4) Set argument explicit names #
IN_ID="$1";
IN_PT="$2";
# (2) Prepare buffer
#--------------------------------------------------------#
# (1) Create buffer path
BUFFER="/tmp/inbuf_$IN_ID";
# (2) Create/Flush buffer
test -f $BUFFER && rm $BUFFER;
touch $BUFFER;
# (3) Launch INPUT server
#--------------------------------------------------------#
(
trap "kill -9 %1 2>/dev/null" INT KILL;
infail=0;
# (1) kill script after 10 failures
while [ $infail -lt 10 ]; do
echo "failures: $infail";
# (2) bind socket to buffer
echo "(.) binding :$IN_PT to $BUFFER";
( nc -lp $IN_PT >> $BUFFER 2> /dev/null && infail="0" || ( infail=`expr $infail + 1`; exit 1 ) || echo " * cannot access :$IN_PT" )&
wait $!;
done;
)&
LOOP_PID=$!;
# (2) Remove buffer + kill loop #
trap "rm $BUFFER 2>/dev/null; kill -9 $LOOP_PID 2>/dev/null" INT KILL;
wait $LOOP_PID;