Lock file via PHP so shell script cannot access it

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jameslabocki
Forum Newbie
Posts: 6
Joined: Tue May 30, 2006 11:08 am
Location: Tampa, FL

Lock file via PHP so shell script cannot access it

Post by jameslabocki »

I have a php process that is called every few minutes to pull values from a database and it writes these values to a file. The values in the file are included by a ksh script, but I want to make sure that while the process is writing the file the ksh script does not pick up the file for execution.

Something like this:
Database <---PULL---> Process.php ----> FILEA <---READ--- script.ksh

I need to be sure that while process.php is writing to FILEA script.ksh can't execute FILEA. I read a bit about flock() and some other things, but I'm not sure if this will lock it at the OS level so script.ksh script can't access. Any help would be much appreciated!

Thanks
James
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I believe it's a file system level lock. You can easily test it by creating a script that locks a file then "remotely" requests itself to check the file's lock state. That may work, otherwise you could write a script that locks a file for 10 minutes, say, and use a shell to check its state.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

jameslabocki wrote:Thank you Feyd,

I tried the following:

Code: Select all

#!/usr/local/bin/php -q
<?PHP

$fp = fopen("/tmp/lock.txt", "w+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock
	 print "locked file, sleeping for 800 seconds....";
   fwrite($fp, "Write something here\n");
   sleep(800);
   flock($fp, LOCK_UN); // release the lock
} else {
   echo "Couldn't lock the file !";
}

fclose($fp);

?>
The file lock.txt was created in temp. Then I just wrote to the file from the command line and it overwrote the contents even when I used flock? Do you have any advice on how to lock the file so I cannot use something like echo > /tmp/lock.txt ?? I think flock() requires all programs to use the same locking mechanism, but obviously shell does not do this.

Thanks
James
hmm. You could build an artificial locking system (certain file exists, the file is "locked") or possibly rename the file while it's being written then rename it back (or just unlink the original and write a new one to a new name renaming after completion.) As long as the .ksh script checks for the file existing, you should be okay.
Post Reply