|
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
# Runs a command asynchronously # calling the callback passing the result nfs_callback() { for i in $(mount -l -t nfs | grep nfs2 | awk -F ":" '{print $1}') fi sleep 1s if [ -f /tmp/$$ ] else 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
Re: Async delegates in... bash!
nexusprime, <> / 7 March, 4:20pm
Not to nit pick, but you probably want to use mktemp to generate filenames in /tmp...
[ Reply (1) ]
raf, <> / 10 March, 3:02am
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) ]
Leave a Comment |