Last active
July 31, 2022 14:53
-
-
Save antranigv/f1ea4747c5a47cb29c68def4827fe531 to your computer and use it in GitHub Desktop.
Meta-programming in Shell | https://weblog.antranigv.am/posts/2022/07/meta-programming-in-shell/
This file contains 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
#!/bin/sh | |
add::fds() | |
{ | |
COMMAND="fds,$1:$COMMAND" | |
} | |
run::fds() | |
{ | |
procstat --libxo=xml -w 5 -f "$1" & | |
PIDS="$!:$PIDS" | |
} | |
export SCRIPTS="fds:$SCRIPTS" |
This file contains 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
#!/bin/sh | |
add::resource() | |
{ | |
COMMAND="resource,$1:$COMMAND" | |
} | |
run::resource() | |
{ | |
procstat --libxo=xml -w 5 -r "$1" & | |
PIDS="$!:$PIDS" | |
} | |
export SCRIPTS="resource:$SCRIPTS" |
This file contains 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
#!/bin/sh | |
set -m | |
usage() | |
{ | |
echo "${0##*/} pid" | |
} | |
# print usage if argc < 1 | |
[ "${#}" -lt "1" ] && usage && exit 1 | |
# load scripts | |
load_scripts() | |
{ | |
for ctl in ./*.ctl.sh; | |
do | |
. "${ctl}" | |
done | |
} | |
# stop the runner by killing the PIDs | |
runner_stop() | |
{ | |
IFS=":" | |
for pid in $1; | |
do | |
kill $pid | |
done | |
exit | |
} | |
# Stop the runner if user sends an input | |
# This is useful if the runner is executed via a controller | |
wait_input() | |
{ | |
read command | |
runner_stop ${PIDS} | |
} | |
# a.k.a. main() | |
runner_start() | |
{ | |
# make sure the process exists | |
_pid="$1" | |
ps -p "${_pid}" 1>/dev/null | |
[ $? != 0 ] && exit 2 | |
# initiate scripts | |
load_scripts | |
# change IFS to : | |
# loop over $SCRIPTS and execute the add hook | |
IFS=":" | |
for ctl in ${SCRIPTS}; | |
do | |
add::${ctl} "${_pid}" | |
done | |
# now that we know the commands, loop over them too! | |
# inside the loop set IFS to "," to set args | |
for cmd in ${COMMAND}; | |
do | |
IFS="," | |
set -- "${cmd}" | |
run::$1 $2 | |
done | |
# Add trap for signals | |
trap "runner_stop ${PIDS}" EXIT SIGINT SIGPIPE SIGHUP 0 | |
# reset IFS | |
unset IFS | |
wait_input | |
} | |
RUNNERDIR=$(dirname "$0") | |
(cd $RUNNERDIR && runner_start "$1") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment