Re: Preventing multiple invocations of script from accessing the same file

From: Martin Gregorie (martin_at_see.sig.for.address)
Date: 11/27/05

Date: Sun, 27 Nov 2005 22:18:58 +0000

Mark Hobley wrote:
> I am writing a CGI script using the Bourne shell. I want to update a file
> based on input obtained.
> If another person is accessing the same web page, the script may
> be invoked a second time, whilst the first ocurrence is still running.
> How can I configure some sort of lock, so that the second copy of the
> script will not continue, until the first copy of the script has done
> the update.
I'd suggest that you don't do it that way.

The easy way to avoid conflicts without using locks is to move all the
critical stuff into a single threaded server which only ever runs as a
single instance and listens on a named pipe or a port.

Your script needs to call a simple program that opens a connection to
the server, passes the request to the server, waits for the response,
closes the connection and quits.

The server should be written to receive a request, process it using
synchronous i/o and return a response. Because the server is single
threaded it will serialize requests: while it is handling one request it
won't accept another connection, let alone overlap it with another
request. The server needs to use poll() to handle the listener port and
the accepted connections but should not use it for anything else apart
from trapping signals. This assumes a single copy of a permanent server
is started at boot time.

The other way to run the server is to let xinetd start the server on
demand and configure xinetd to allow only one copy of the server to be
started. This makes the server as easy to write as a normal filter. It
gets the request via stdin and writes the response to stdout. It doesn't
use poll() at all.


martin@   | Martin Gregorie
gregorie. |
org       | Zappa fan & glider pilot