Created
October 9, 2013 05:31
-
-
Save nz/6896653 to your computer and use it in GitHub Desktop.
Nerd sniped by named pipes
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 | |
# clear old pipe and lock | |
rmdir worklock 2>/dev/null | |
rm work | |
if [[ ! -p work ]]; then | |
mkfifo work | |
else | |
dd if=work of=/dev/null | |
fi | |
# define a worker loop | |
function worker { | |
workerid=$1 | |
job="" | |
while [[ $job != "quit" ]] ; do | |
# acquire a really naive lock so we don't race others for the fifo | |
if mkdir worklock 2>/dev/null ; then | |
# read the job off the pipe | |
read job < work | |
# unlock the queue so others can work | |
rmdir worklock | |
# do the work | |
case "$job" in | |
"quit") | |
echo "worker $workerid: quitting" | |
;; | |
*) | |
echo "worker $workerid: $job" | |
sleep 3 # simulate work | |
;; | |
esac | |
else | |
# failed to get the lock, wait and try again | |
sleep 0.01 | |
fi | |
done | |
} | |
# start two workers | |
worker 1 & | |
worker 2 & | |
worker 3 & | |
worker 4 & | |
# send them jobs | |
function queue { | |
echo $* >> work | |
sleep 0.01 | |
} | |
queue "job 1" | |
queue "job 2" | |
queue "job 3" | |
queue "job 4" | |
queue "job 5" | |
queue "job 6" | |
queue "quit" | |
queue "quit" | |
queue "quit" | |
queue "quit" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment