91 lines
2.0 KiB
Plaintext
91 lines
2.0 KiB
Plaintext
|
#!/bin/bash
|
||
|
#!/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\ttrigger-wait <key> <port>\n\n\e[1mARGUMENTS\e[0m\n\t<key>\tThe key of the trigger (client must match it)\n\t<port>\tTo port to listen to\n" && exit 1;
|
||
|
|
||
|
# (3) Check @PORT range #
|
||
|
MIN_PORT=1024;
|
||
|
MAX_PORT=49151;
|
||
|
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 #
|
||
|
TRIGGER_KEY="$1";
|
||
|
TRIGGER_PORT="$2";
|
||
|
|
||
|
# (5) Create a temporary file #
|
||
|
TMPFILE="/dev/shm/trigger_wait_${TRIGGER_KEY}_pid";
|
||
|
|
||
|
|
||
|
# (6) Define on-exit routine #
|
||
|
LOOP_PID="";
|
||
|
on_exit(){
|
||
|
|
||
|
echo "- killing loop";
|
||
|
kill -INT $LOOP_PID 2>/dev/null;
|
||
|
|
||
|
echo "- killing main listener ($TRIGGER_PID)";
|
||
|
kill -INT $TRIGGER_PID 2>/dev/null;
|
||
|
|
||
|
# delete tmp file
|
||
|
echo "- deleting tmp file";
|
||
|
rm $TMPFILE 2>/dev/null;
|
||
|
|
||
|
exit 1;
|
||
|
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
# (2) Launch pool listener
|
||
|
#--------------------------------------------------------#
|
||
|
# (1) Bind-input #
|
||
|
echo -e "\e[32m+\e[0m listen $TRIGGER_PORT";
|
||
|
$ROOT/bind-input trigger $TRIGGER_PORT > $TMPFILE;
|
||
|
TRIGGER_PID="`cat $TMPFILE`";
|
||
|
|
||
|
|
||
|
|
||
|
# (3) Launch pool manager
|
||
|
#--------------------------------------------------------#
|
||
|
# infinite listener
|
||
|
(
|
||
|
trap "on_exit;" HUP INT KILL TERM;
|
||
|
|
||
|
while true; do
|
||
|
|
||
|
# Listen on port @TRIGGER_PORT
|
||
|
MSG=`$ROOT/read trigger`;
|
||
|
|
||
|
# Do nothing if empty msg
|
||
|
test -z "$MSG" && sleep .5 && continue;
|
||
|
|
||
|
echo -e " + received '\e[33m$MSG\e[0m'";
|
||
|
|
||
|
# If wrong key
|
||
|
test "$MSG" != "$TRIGGER_KEY" && echo " + wrong key" && sleep .5 && continue;
|
||
|
|
||
|
# If valid key
|
||
|
echo " + trigger received" && echo -e "\e[31m+\e[0m stop listening on $TRIGGER_PORT" && break;
|
||
|
|
||
|
done;
|
||
|
|
||
|
)&
|
||
|
LOOP_PID=$!;
|
||
|
|
||
|
# (4) Set exit management
|
||
|
#--------------------------------------------------------#
|
||
|
# (1) Set trap for "exit" signals #
|
||
|
trap "kill -INT $LOOP_PID 2>/dev/null;" HUP INT KILL TERM;
|
||
|
|
||
|
# (2) Wait for main loop to end
|
||
|
wait $LOOP_PID;
|
||
|
|
||
|
on_exit;
|