Page 1 of 1

locking files

Posted: Sat Apr 02, 2005 6:35 am
by brandan
i have an issue. on a website i'm developing i have a script that accesses a text file every time the page is viewed, and if it finds any specific strings it parses them and places the parsed information into an sqlite database. the reason i have it set up this way, as opposed to on a separate page, is so that i don't have to update the stuff manually. there is a problem, though. if more than one person accesses the page while the script is running it will create duplicate entries. the text file being read from is deleted after each time it's read to keep things speedy.

one of the solutions suggested to me was to lock the file, so i tried flock(), but apparently it does not work the way i need it to. here's the script that i created for the process (lines 3, 4 and 32 show how i use flock):

Code: Select all

$fp = fopen('playlist.inc', 'r');
	if (flock($fp, LOCK_EX)) {
		while(!feof($fp)) {
			useless crap here.
		}
		flock($fp, LOCK_UN);
	}
	fclose($fp);
	unlink('playlist.inc');
i really don't see any other way of doing it. basically i just want to keep parallel threads from being able to access the file after the first thread is executed.

the script will still let other scripts access the file while it's reading it. i also get this error:

[client 127.0.0.1] PHP Warning: unlink(playlist.inc) [<a href='function.unlink'>function.unlink</a>]: Permission denied in C:\\Program Files\\Apache Group\\Apache2\\htdocs\\update.php on line 37

which i assume is the actual result of locking the file. i believe this is preventing any writing from being done to the file, but what i need is for any reading to be prevented, as well.

Posted: Sat Apr 02, 2005 7:27 am
by brandan
ok, i just got a good tip for a solution. basically when the script starts it checks for a .lock file, if the file doesn't exist it generates it, if it does exist the script halts. the .lock (or whatever i end up naming it) is removed after the script finishes.

RE: Locking Files

Posted: Sat Apr 02, 2005 10:49 pm
by marike
Don't you think you might be better off using SQLite to replace the flat file as well? Even if you're able to lock 'playlist.inc', what happens if two scripts try to acquire a lock at the same time? The result would be a race condition, where two processes are competing for locks, causing nothing but problems.

If you don't want to use make a permanant DB table, you can use SQLite and an in-memory temporary database. I think it might be simpler, and more efficient in the long run.

Sorry I could help with your specific problem, Good luck