This may not surprise some of you but, believe it or not, you can write very simple asynchronous delegates in plain old bash. Yeah that's right, BASH.

Here's the scenario, let's say you have to perform a task that might take a long time (let's pretend you need to check the health of an nfs server prior to attempting to mount exports from it) but you do not want to block the main "process" waiting for it, here's how something like that can be implemented:

###################################################
# ASYNC NFS CHECK
# Rafael Ferreira <raf@ophion.org>
###################################################

# CONFIG FLAG - whether NFS has been checked or not
NFS_OK=1

# Runs a command asynchronously
# $1 is the command to run
# $2 is the callback function
async_run() {
        {
                $1 &>/dev/null

                # calling the callback passing the result
                $2 $?
        }&
}

nfs_callback() {
        if [ $1 == "0" ]
        then
                touch /tmp/$$
        fi
}

for i in $(mount -l  -t nfs | grep nfs2 | awk -F ":" '{print $1}')
do
        if [ $NFS_OK == "1" ]
        then
             async_run "/usr/sbin/rpcinfo -p $i" nfs_callback
             disown

        fi
done

sleep 1s

if [ -f /tmp/$$ ]
then
        echo "NFS OK"

else
        echo "NFS NOT OK"
fi
 

In a nutshell, async_run() is where all the action happens. It takes a string parameter of a command to be run and a callback function to be dispatched once the command is done. On the example above, I decided to block the main process and wait for the async call to return for at most 1 sec, this allows me to have constant execution O(1), no matter how long the async task takes.

Yeah, I know this is pretty silly, but hey, I like it.

rafael | General | 6 March, 11:00am
nexusprime, <> / 7 March, 4:20pm  
avatar

Not to nit pick, but you probably want to use mktemp to generate filenames in /tmp...

[ Reply (1) ]
raf, <> / 10 March, 3:02am  
avatar

Yeah I would generally agree but, in this case, the pid ($$) should be fairly safe since you are solely interested in preventing concurrency.

[ Reply (0) ]
Darcy Booker, <> / 13 November, 6:14am  
avatar

lzkuigo8wcuo764i

[ Reply (0) ]

Leave a Comment







Comment XML feeds: RSS | Atom