473,698 Members | 2,445 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

flock won't non-block at all

Hi there,

I'm trying to just prevent multiple instances of a script running.

I would have thought that the following code would do this for me.

<php
$fp = fopen("foo.txt" , "w");
flock($fp, LOCK_EX + LOCK_NB) or die ("Could not get lock!\n");
echo "Got lock!\n";
sleep(10);
flock($fp, LOCK_UN);
?>

The first script to run would obtain the lock on the file, and would
execute.
Any other scripts would fail immediately (because of my non-blocking
LOCK_NB).

But it seems that ALL of my scripts just wait, and ALL of them end up
printing "Got lock!"

Can anyone help me out?

I am on winXP with php5.

Cheers,
Sven.

Sep 21 '06 #1
7 4484
I think you need to open the file with w+ e.g. $fp = fopen("foo.txt" ,
"w+");

Give it ago see what happends, I might be wrong.

sv***********@g mail.com wrote:
Hi there,

I'm trying to just prevent multiple instances of a script running.

I would have thought that the following code would do this for me.

<php
$fp = fopen("foo.txt" , "w");
flock($fp, LOCK_EX + LOCK_NB) or die ("Could not get lock!\n");
echo "Got lock!\n";
sleep(10);
flock($fp, LOCK_UN);
?>

The first script to run would obtain the lock on the file, and would
execute.
Any other scripts would fail immediately (because of my non-blocking
LOCK_NB).

But it seems that ALL of my scripts just wait, and ALL of them end up
printing "Got lock!"

Can anyone help me out?

I am on winXP with php5.

Cheers,
Sven.
Sep 22 '06 #2
NC
sv***********@g mail.com wrote:
>
I'm trying to just prevent multiple instances of a script running.
....
I am on winXP with php5.
Read the documentation:

On some operating systems flock() is implemented at the process
level. When using a multithreaded server API like ISAPI you may
not be able to rely on flock() to protect files against other PHP
scripts running in parallel threads of the same server instance!

http://www.php.net/flock

This is the bad news. The good news is that you don't necessarily
need flock() for this. Here's a possible workaround:

$file = 'foo.txt';
if (file_exists($f ile)) {
$time = date('Y-m-d H:i:s', trim(file_get_c ontents($file)) );
die('Another instance is running since ' . $time);
}
$fp = fopen($file, 'w');
fwrite($fp, time());
fclose($fp);
// the script goes here...
unlink($file);

Cheers,
NC

Sep 22 '06 #3
On 22 Sep 2006 09:30:54 -0700, "NC" <nc@iname.comwr ote:
>This is the bad news. The good news is that you don't necessarily
need flock() for this. Here's a possible workaround:

$file = 'foo.txt';
if (file_exists($f ile)) {
$time = date('Y-m-d H:i:s', trim(file_get_c ontents($file)) );
die('Another instance is running since ' . $time);
}
$fp = fopen($file, 'w');
Although the fun then begins when you hit the (admittedly short-duration) race
condition here...
>fwrite($fp, time());
fclose($fp);
// the script goes here...
unlink($file );
... or the never-released lock when the script dies before reaching here :-(

--
Andy Hassall :: an**@andyh.co.u k :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Sep 22 '06 #4
NC
Andy Hassall wrote:
>
$fp = fopen($file, 'w');

Although the fun then begins when you hit the (admittedly
short-duration) race condition here...
You are absolutely right, but how else could you work around the file
locking issue on Windows?

Cheers,
NC

Sep 23 '06 #5
On 23 Sep 2006 09:46:38 -0700, "NC" <nc@iname.comwr ote:
>Andy Hassall wrote:
>>
$fp = fopen($file, 'w');

Although the fun then begins when you hit the (admittedly
short-duration) race condition here...

You are absolutely right, but how else could you work around the file
locking issue on Windows?
Not sure whether there's anything convenient in PHP itself that'll give you a
per-thread reliable and atomic lock. The win32 API has plenty of
synchronisation functions that would work, perhaps one could be called using
the win32api extension?

In some situations where I've needed locks and have had to work across Windows
and NFS filesystems (which have their own file locking quirks) I've used locks
within a database (user-defined locks in Oracle) - but in those cases I was
connecting to a database already.

--
Andy Hassall :: an**@andyh.co.u k :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Sep 24 '06 #6
Andy Hassall wrote:
>
$fp = fopen($file, 'w');

Although the fun then begins when you hit the (admittedly
short-duration) race condition here...
You are absolutely right, but how else could you work around the file
locking issue on Windows?

Not sure whether there's anything convenient in PHP itself that'll give you a
per-thread reliable and atomic lock. The win32 API has plenty of
synchronisation functions that would work, perhaps one could be called using
the win32api extension?

In some situations where I've needed locks and have had to work across Windows
and NFS filesystems (which have their own file locking quirks) I've used locks
within a database (user-defined locks in Oracle) - but in those cases I was
connecting to a database already.
Thanks for the tips guys, here's a rundown of the end result:
It turns out that whenever I was testing my little example above, I was
opening the script through a browser. For some reason the flock() never
seems to work for me this way, however when I ran it from the
command-line php things sorted themselves out. My application was
going to run in the background anyway, so I've ended up getting it to
work by having my web php call command-line php as a background
process.

The file check/create/unlink option is a good one, but my script is one
that will fire occassionaly, but will sit in a while loop for hours at
a time. So, the dead-script problem is a real one here.

Cheers for the input people,
Sven.

Sep 26 '06 #7
NC
Sven wrote:
>
It turns out that whenever I was testing my little example
above, I was opening the script through a browser. For
some reason the flock() never seems to work for me this
way, however when I ran it from the command-line php
things sorted themselves out.
Well, the reason is that inder Windows, scripts executed by an HTTP
server (such as Apache or IIS) run in threads, so it's possible for
multiple instances of a script to run under the same process ID (even
though the thread ID is different). With command-line execution, no
threading takes place; each instance has its own process ID...

Cheers,
NC

Sep 26 '06 #8

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

Similar topics

0
2276
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);
0
2070
by: Daniel Brunthaler | last post by:
hi, i've a problem with file locking. seems that flock() and gzopen() do not work together. i get the error (or warning) message ... Warning: flock(): cannot represent a stream of type ZLIB as a File Descriptor in ... when using flock() after gzopen().
14
3166
by: deko | last post by:
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");
3
4773
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 filesystem.
4
7892
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
2810
by: siliconmike | last post by:
I've scoured over manual page for flock on http://in2.php.net/flock but I can't understand a few things: 1. will flock wait until a different process releases the lock ? 2. please clarify this line: " If you don't want flock() to block while locking, add LOCK_NB " what does "block" mean above?
4
19163
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
3645
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
1744
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
4209
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 in 60 seconds) are removed. Using a combination of flock, microsecond sleeps, loops and the flash...
0
8604
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9160
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9029
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8897
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8862
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7729
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2331
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2002
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.