Skip to content

Instantly share code, notes, and snippets.

@dnmfarrell
Last active February 13, 2023 16:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
A forking bash program to distribute input among workers
#!/bin/bash
# Copyright 2023 David Farrell
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
set -euo pipefail
declare -i num_workers=1
declare -i num_fifos=0
declare -i next_fifo=1
declare -a fifos=("") # zeroth unused
new_fifo() {
local fn="${TMPDIR-/tmp}/forklift-$1"
fifos[$1]="$fn"
num_fifos=$((num_fifos+1))
mkfifo "$fn"
eval "tail -f '$fn' --pid $$ | ${cmd/\{\{w\}\}/$1} &"
}
cleanup() {
for i in $(seq 1 ${num_fifos});do
rm -f "${fifos[$i]}"
done
}
trap cleanup EXIT
# process args
while getopts "w:" opt;do
case "$opt" in
'w') num_workers="$OPTARG";;
esac
done
shift $((OPTIND-1))
if [ $# -ne 1 ]; then
echo -e "Must provide 1 command. Usage:\n\tforklift [-w #] command"
exit 1
fi
declare cmd="$1"
# process input
while read -r;do
((next_fifo > num_fifos)) && new_fifo $next_fifo
echo "$REPLY" > "${fifos[$next_fifo]}"
if ((next_fifo==num_workers)); then
next_fifo=1
else
next_fifo=$((next_fifo+1))
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment