473,574 Members | 3,052 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

flock and reading file into array

Do I need to use flock() when reading a file into an array? It's possible that
the file in question could be open at the time the file('filename' ) request is
made. I realize flock() is required when opening a file with fopen() when there
is contention for the file:

$fp=fopen($ctr, 'w');
//only write if we can get lock on file
if (flock($fp, LOCK_EX))
{
fwrite($fp, "0");
flock($fp, LOCK_UN);
}
else
{
//try again... how???????
}
fclose($fp);

but is it required when reading a file into an array?

$totals=file('v isinterval');
$var=explode('| ',$totals[0]);
$i24h = number_format($ var[0]);
$i30d = number_format($ var[1]);
$i365d = number_format($ var[2]);

also - if the attempt to get a lock on the file fails (in the first example),
how do I retry?

Thanks in advance.
Jul 17 '05 #1
14 3150
> but is it required when reading a file into an array?
Yes, flock is required in your situation. Using 'file()' does not change
anything.
also - if the attempt to get a lock on the file fails (in the first example),
how do I retry?

I recommend blocking variant of 'flock()'

DG
--
Ask yourself: are you ready for the enterprise ?
Jul 17 '05 #2
Thanks for the tip - I'll check it out.

"Drazen Gemic" <dg****@net.net > wrote in message
news:pa******** *************** *********@net.n et...
but is it required when reading a file into an array?

Yes, flock is required in your situation. Using 'file()' does not change
anything.
also - if the attempt to get a lock on the file fails (in the first example), how do I retry?

I recommend blocking variant of 'flock()'

DG
--
Ask yourself: are you ready for the enterprise ?

not if the only language I've got is php...
Jul 17 '05 #3
deko wrote:
Do I need to use flock() when reading a file into an array? It's possible that
the file in question could be open at the time the file('filename' ) request is
made. I realize flock() is required when opening a file with fopen() when there
is contention for the file:

$fp=fopen($ctr, 'w');
//only write if we can get lock on file
if (flock($fp, LOCK_EX))
{
fwrite($fp, "0");
flock($fp, LOCK_UN);
}
else
{
//try again... how???????
}
fclose($fp);

but is it required when reading a file into an array?

$totals=file('v isinterval');
$var=explode('| ',$totals[0]);
$i24h = number_format($ var[0]);
$i30d = number_format($ var[1]);
$i365d = number_format($ var[2]);

also - if the attempt to get a lock on the file fails (in the first example),
how do I retry?


I think you can't flock() a file() operation -- no such indication on
the manual. Anyway file() just reads the file, it will never write
anything to it.

If you're sure the file exists, and file() fails, just wait a few
microseconds and try again (you can use the same method to retry a lock
that failed):

<?php
$totals = false;
$num_tries = 10;
while (($totals === false) && ($num_tries != 0)) {
$totals = file('visinterv al');
usleep(100);
--$num_tries;
}
?>
--
USENET would be a better place if everybody read: : mail address :
http://www.catb.org/~esr/faqs/smart-questions.html : is valid for :
http://www.netmeister.org/news/learn2quote2.html : "text/plain" :
http://www.expita.com/nomime.html : to 10K bytes :
Jul 17 '05 #4
> I think you can't flock() a file() operation -- no such indication on
the manual. Anyway file() just reads the file, it will never write
anything to it.

If you're sure the file exists, and file() fails, just wait a few
microseconds and try again (you can use the same method to retry a lock
that failed):

<?php
$totals = false;
$num_tries = 10;
while (($totals === false) && ($num_tries != 0)) {
$totals = file('visinterv al');
usleep(100);
--$num_tries;
}
?>

Thanks, that helped. Here's what I've come up with:

<?php
$ctr = 'counter';
$got_it = false;
$timeout = 10;
$fp=fopen($ctr, 'w');
while (($got_it === false) && ($timeout != 0))
{
if (flock($fp, LOCK_EX))
{
$counter = file($ctr); //do file operation after getting lock
$curct = each($counter);
fwrite($fp, "0");
flock($fp, LOCK_UN);
fclose($fp);
$got_it=true;
}
else
{
usleep(1000);
--$timeout;
}
}
if (!$got_it)
{
$fp=fopen('ctr_ last_update', 'w');
fwrite($fp,date ("F d Y H:i:s.", fileatime($ctr) ));
//echo date("F d Y H:i:s", fileatime($ctr) );
exit;
}
?>

Seems to work... first, I get a lock on counter - if I can't, then I can't
update the counter - so log the time of failure and quit. What do you think?
Also, as for error handling, can you point me to any resources for best
practices regarding error handling in php?

thx

Jul 17 '05 #5
deko wrote:
<?php
$ctr = 'counter';
$got_it = false;
$timeout = 10;
$fp=fopen($ctr, 'w');
if ($fp === false) die("Unable to open $ctr for writing.\n");
while (($got_it === false) && ($timeout != 0))
{
if (flock($fp, LOCK_EX))
{
$counter = file($ctr); //do file operation after getting lock
# Ah! seems you can lock the file for reading after all :)
# but you're not testing if the function failed ...

if ($counter === false) die("Unable to read $ctr.\n");
$curct = each($counter);
# $curct is an array, you're not using it anywhere. Why do this at all?
fwrite($fp, "0");
# not tested for failure. I'd do
if (!fwrite($fp, "0")) die("Unable to write to $ctr.\n");
flock($fp, LOCK_UN);
# not tested for failure
fclose($fp);
# not tested for failure
$got_it=true;
}
else
{
usleep(1000);
--$timeout;
}
} if (!$got_it)
{
# $fp is still opened and pointing to $ctr! You never closed it.
$fp=fopen('ctr_ last_update', 'w');
# Are you sure you want to clear the file?
# ... maybe opening in append mode would be better
fwrite($fp,date ("F d Y H:i:s.", fileatime($ctr) ));
# no locking now? :)
# anyway, you're not testing the functions for failure.

# remember to close the file
if (!fclose($fh)) die("Unable to close $ctr.\n");

# I do this with error_log() [and never worried about whether it locks
# the file -- maybe I should]

# instead of
# fopen()
# fwrite()
# fclose()
if (!error_log(dat e("F d Y H:i:s.", fileatime($ctr) ), 3, 'ctr_last_updat e')) {
die("Unable to write error_log.\n");
}
//echo date("F d Y H:i:s", fileatime($ctr) );
exit;
}
?>

Seems to work... first, I get a lock on counter - if I can't, then I can't
update the counter - so log the time of failure and quit. What do you think?
seems ok, though a little short on tests for failure (which you should
always do)
Also, as for error handling, can you point me to any resources for best
practices regarding error handling in php?


Sorry, no. I don't know any.
--
USENET would be a better place if everybody read: : mail address :
http://www.catb.org/~esr/faqs/smart-questions.html : is valid for :
http://www.netmeister.org/news/learn2quote2.html : "text/plain" :
http://www.expita.com/nomime.html : to 10K bytes :
Jul 17 '05 #6
> I think you can't flock() a file() operation -- no such indication on

'flock()' is just a wrapper for system call(s). To read a file into
array, a file MUST be open. 'file()' hides that functionality, bu it
opens file as well.
the manual. Anyway file() just reads the file, it will never write
anything to it.


THe problem is that other process might write to file, while reading
operation takes place. That would lead to inacurate result, and that's
why 'flock()' is needed.
--
Ask yourself: are you ready for the enterprise ?
Jul 17 '05 #7
> > $ctr = 'counter';
$got_it = false;
$timeout = 10;
$fp=fopen($ctr, 'w');
if ($fp === false) die("Unable to open $ctr for writing.\n");


do I really need this? see revised code below
while (($got_it === false) && ($timeout != 0))
{
if (flock($fp, LOCK_EX))
{
$counter = file($ctr); //do file operation after getting lock


# Ah! seems you can lock the file for reading after all :)


yes, but I don't think it matters - as you mentioned before - all this does is
read - no locks required.
# but you're not testing if the function failed ...
see revised code below
if ($counter === false) die("Unable to read $ctr.\n");
$curct = each($counter);
# $curct is an array, you're not using it anywhere. Why do this at all?


$curct is used a bit later in the script

snip...
# Are you sure you want to clear the file?
yes.
seems ok, though a little short on tests for failure (which you should
always do)


Thanks for the detailed post. I appreciate it.
* I use error_reporting (0) at the top of this script - if the couter breaks,
I'll know it by watching the output on the html page. I can live with the
counter being off line for a while.

* as for tests for failure, isn't that all wrapped up in the last if statement:

if (!$got_it)
{
$fp=fopen('visi nterval_missed' , 'a');
fwrite($fp,date ("F d Y H:i:s.", fileatime($ctr) ));
exit; <======= *** bail out here if problems ****
}
=========== REVISED CODE =============
$got_it = false;
$timeout = 10;
$viscounter = file($ctr);
$curct = each($viscounte r);
$fp=fopen($ctr, 'w');
while (($got_it === false) && ($timeout != 0))
{
if (flock($fp, LOCK_EX))
{
fwrite($fp, "0");
flock($fp, LOCK_UN);
$got_it = true;
}
else
{
usleep(100000);
--$timeout;
}
}
fclose($fp);
//if cd not get lock after 10 tries (1 sec.),
//skip this interval and record failure
if (!$got_it)
{
$fp=fopen('visi nterval_missed' , 'a');
fwrite($fp,date ("F d Y H:i:s.", fileatime($ctr) ));
exit;
}
Jul 17 '05 #8
> THe problem is that other process might write to file, while reading
operation takes place. That would lead to inacurate result, and that's
why 'flock()' is needed.


10-4

I know this is a bit of a switch of topics, but I was wondering if you know why
I'm getting this error:

Warning: Failed opening 'viscount' for inclusion
(include_path=' .:/usr/share/pear') in /home/post/public_html/index.php on line
69

the code is at the bottom of one of the pages in my site and is supposed to call
this counter script I've been working on

<?php
include ('viscount');
?>
</body>
</html>

what is usr/share/pear ???
Jul 17 '05 #9
> I know this is a bit of a switch of topics, but I was wondering if you know
why
I'm getting this error:


nevermind.... I figured it out - the problem is I need some sleep...
Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2261
by: Marc | last post by:
Hello, when using flock() I get a permission denied error: Warning: fopen("<filename>", "r+") - Permission denied in <pathtofile> on line 7 I do this: $fileToOpen=substr($PHP_SELF, strrpos($PHP_SELF,"/")+1); $fileHandle=fopen($fileToOpen, 'r+') or die($php_erormsg);
3
4769
by: Rex Karz | last post by:
Newbie here. I interpret the fine print at http://us2.php.net/manual/en/function.flock.php to mean that flock() does not work where the file being locked is on an NFS filesystem. The commentary following the "official" description of flock() offers numerous circumventions broken flock() where the file needing atomic access is on an NFS...
4
7874
by: writeson | last post by:
Hi all, I've got a PHP program that I've added flock() to in order to protect multiple scripts trying to write to the same file. After I added the flock() to the code the performance of the code went way down. Can anyone tell me if calling flock() on a file handle is particularly slow? Thanks, Doug
3
1736
by: Jonathan N. Little | last post by:
Hello, I am making the not so smooth transition from Perl to PHP and my question concerns file locking. PHP has a myriad of file parsing functions an many do not appear do give access to a file handle for flock, i.e., file(), parse_ini_file()...convenient since they dump into an array, I have data in TSV (tab separated value) files. Do the...
4
19154
by: Time Waster | last post by:
Is this a stupid use of flock: FILE *fp=fopen(SOME_FILE_CONSTANT,"r+"); flock(fileno(fp),LOCK_EX); something important here, including reads and a write to fp flock(fileno(fp),LOCK_UN); fclose(fp); Does this accomplish real locking, or just narrow down the race quite a bit? (Race existing between the unlock and the
2
2337
by: yawnmoth | last post by:
If I do flock($fp, LOCK_EX) on a file and another user tries to do file_get_contents on that file while it's locked, will file_get_contents block until the lock has been removed?
2
3641
by: xucs007 | last post by:
I ran following 2 programs (lock1, lock2) at almost same time, to write either "123456", or "222" to file "aaa" at the same time. But I often just got "222456" in "aaa" . Is this a bug of python fcntl module ? See 2 programs I ran: #!/usr/bin/env python import fcntl, time
1
1742
by: Seb | last post by:
I'm trying to implement a file server using the code below. However the locking doesn't work. I can delete while put'ing a file. Anyone got an idea about why? best regards, seb
6
4202
by: Bill H | last post by:
I am wondering if this is possible. I have a file that is accessed by multiple users and keeps track of activity (the file is polled by flash every 2 seconds). As users leave, the flash program tells the php program to remove them from the activity file, and as users access this activity file, users who have timed out (haven't been heard from...
0
8272
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7859
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8137
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5657
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5336
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3774
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2274
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1369
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1101
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.