Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Exclusive file access and flock on Windows and UNIX

Status
Not open for further replies.

Tyger

Programmer
Sep 19, 2001
21
GB
I frequently find myself writing scripts which access text files as a form of basic database. My understanding is that the file should be locked to grant a script instance exclusive file access and prevent problems if two script instances try to access the same file simultaneously:

open(TXT, &quot;< text.txt&quot;);
flock(TXT,2);

# Read file etc.

flock(TXT,8);
close TXT;

I can understand the need for this when writing to a file but is it really necessary when reading? Surely the OS the webserver is running on can handle multiple simultaneous reads, especially in the case of UNIX.

This is presenting a problem with my current project where I would like to use perl to send a file to STDOUT to effectively force the user to download a file rather than just using an html link.

If I were to use a link, multiple users could downlaod the same file simultaneously. If I use the script method with flock then only one instance of the script (and thus one user) can download the file concurrently. Not a problem with a 30k image, but a 20MB software update will be.

On the same subject, just what does happen if flock is in use and a second script instance tries to access a locked file? Does the second script abort, carry on executing without opening the file (potentially resulting in errors unless a check is made to ensure the file was successfully accessed) or wait until the file becomes available and then resume? I have always assumed the latter but do not know if this is the case.

Many thanks,
Tyger.
 
The way you're using it, [tt]flock[/tt] would block until the lock is received. You can use [tt]flock(TXT, 6)[/tt] to have it return immediately -- you would then need to check the return value, with a false return indicating that the lock was not achieved.

You are correct, though. If you're just reading, and the file is not being changed elsewhere, you do not need to worry about locking it.

If the file is being changed elsewhere, by an application that is not using a lock, getting the lock might not even help.
 
That's exactly what I was hoping.

thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top