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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Concurrent File access and CGI scripts 1

Status
Not open for further replies.

mbaranski

Programmer
Nov 3, 2000
421
US
I've a CGI script that takes an email address and a boolean and depending on the boolean adds/removes the address from a mailing list. The mailing list is a flat text file with 1 address per line.

When an item is removed, I read every entry except ones that match the address to remove and write them to a temp file, then rename the temp file. This gets rid of the addresses that I don't want.

But, what happens if 2 people run the program, and one person's overlapps the second. How do I do a waiting thing to set the program to wait until no other processes are using the file? Any ideas? Is there a better way to do this? How exactly is file I/O done in perl (as far as it affects this problem?).

Thanks
MWB.

Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
 
You can use flock to get the desired behavior. Given a number processes that all use 'flock' on a file, when one locks the file, any subsequent attempts to lock the file wait in line until the first finishes and unlocks the file.
The following was taken from the Camel book and tweaked slightly.

Code:
$LOCK_EX = 2;
$LOCK_UN = 8;

sub lock
{
# establish an exclusive lock
flock HANDLE, $LOCK_EX;

# in case, another process appended while
# this process waited for a lock.
seek HANDLE, 0, 2;
}

sub unlock
{
flock HANDLE $LOCK_UN;
}

lock();
print HANDLE "Some stuff to the file.";
unlock();


Also, see perldoc -f flock.

HTH


keep the rudder amid ship and beware the odd typo
 
Thanks, I found that right after I posted.


Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top