Re: Add locking to FIFO (named pipe) client/server?
Grant wrote:
> [...]
>
> An ad hoc CLI query looks like this:
>
> grant@deltree:~$ echo "220.240.123.123" > /var/run/ip2c_query
>
> grant@deltree:~$ cat /var/run/ip2c_reply
> 220.240.0.0/16:AU :Australia:3706716160:3706781695
>
>
> My problem is that there's no file locking, a cron job runs each hour
> throwing several hundred queries at the server via the FIFOs, if I
> happen to run a manual query at that time the thing may lockup.
>
> I'm looking for ideas on how to add exclusive access locking?
Grant,
it should be enough to set up a lockfile each time the client is about
to send a query and remove it just after the reply is read. File
existence check and its respective creation should be done atomically.
There may be some better way to do it in gawk, but this should
generally work well (with bash set as the default shell):
system("(set -o noclobber; echo > /var/run/ip2c_lock) 2>/dev/null")
As long as the above statement's result is 1, the FIFO is locked by
another client. Once the result is 0, we have just locked the FIFO for
ourselves. Don't forget to remove it after the reply is read.
The simple script for manual query utilizing the locking mechanism
would look something like this:
#!/bin/sh
# Usage: ip2c IPADDR
# Atomic file check and creation mechanism in bash
set -o noclobber
while ! echo > /var/run/ip2c_lock; do usleep; done 2>/dev/null
# Remove the lock file no matter how we die
trap "rm -f /var/run/ip2c_lock" EXIT SIGINT SIGTERM
echo "$1" > /var/run/ip2c_query
cat /var/run/ip2c_reply
Hope this s,
Jan
|