Futures and promises can be approximated in bash with the help of a named pipe, process substitution, and i/o redirection. Here's a way to do it:
#!/bin/bash
# get a name for the fifo in /tmp
fifo_name=$(mktemp -u)
# create the fifo
mkfifo -m 600 ${fifo_name}
# redirect this process's fd 3 to cat the fifo
# this is sort of like making fd 3 into a future
exec 3< <(cat ${fifo_name})
borf() {
sleep 1
# write to the fifo (like writing to the promise)
echo "borf" > ${fifo_name}
}
# run the borf function in the background
borf &
echo "waiting for borf..."
# read from fd 3, this will block (like waiting on the value of the future)
read <&3 line
echo $line
This technique can be used to wait asynchronously for a value when there is a need to background an operation and wait for its result.
Friday, April 20, 2018
Subscribe to:
Posts (Atom)