note 127484 added to splfileobject.flock
| From: | AhmedRain at main dot php dot net | Date: | Thu, 11 Aug 2022 22:25:30 +0000 |
| Subject: | note 127484 added to splfileobject.flock | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219421@lists.php.net to get a copy of this message | ||
@digitalprecision What you said is not completely true, ftruncate(0); is needed if there was a write
to the file before the lock is acquired. You also may need fseek(0); to move back the file pointer
to the beginning of the file
<?php
$file = new SplFileObject("/tmp/lock.txt", "w");
$file->fwrite("xxxxx"); // write something before the lock is acquired
sleep(5); // wait for 5 seconds
if ($file->flock(LOCK_EX)) { // do an exclusive lock
$file->fwrite("Write something here\n");
$file->flock(LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
?>
"lock.txt" content:
xxxxxWrite something here
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.133 (proxied: 2a02:cb80:403b:8a2e:1d29:beea:683a:e641)
----
Manual Page -- https://php.net/manual/en/splfileobject.flock.php
Edit -- https://main.php.net/note/edit/127484
Del: integrated -- https://main.php.net/note/delete/127484/integrated
Del: useless -- https://main.php.net/note/delete/127484/useless
Del: bad code -- https://main.php.net/note/delete/127484/bad+code
Del: spam -- https://main.php.net/note/delete/127484/spam
Del: non-english -- https://main.php.net/note/delete/127484/non-english
Del: in docs -- https://main.php.net/note/delete/127484/in+docs
Del: other reasons-- https://main.php.net/note/delete/127484
Reject -- https://main.php.net/note/reject/127484
Search -- https://main.php.net/manage/user-notes.php