dongmaxi6763 2011-02-05 13:04
浏览 22
已采纳

如何在PHP中锁定文件?

I'm trying to create a PHP file, which wouldn't run if it's already running. Here's the code I'm using:

<?php

class Test {
    private $tmpfile;

    public function action_run() {
        $this->die_if_running();
        $this->run();
    }

    private function die_if_running() {
        $this->tmpfile = @fopen('.refresher2.pid', "w");

        $locked = @flock($this->tmpfile, LOCK_EX|LOCK_NB);
        if (! $locked) {
            @fclose($this->tmpfile);
            die("Running 2");
        }
    }

    private function run() {
        echo "NOT RUNNNING";
        sleep(100);
    }
}

$test = new Test();
$test->action_run();

The problem is, when I run this from console, it works great. But when I try to run it from browser, many instances can run simultaneously. This is on Windows 7, XAMPP, PHP 5.3.2. I guess OS is thinking that it's the same process and thus the functionality falls. Is there a cross-platform way to create a PHP script of this type?

  • 写回答

2条回答 默认 最新

  • dongpa2000 2011-02-05 13:15
    关注

    Not really anything to promising. You can't use flock for that like this.

    You could use system() to start another (php) process that does the locking for you. But drawbacks:

    • You need to do interprocess communication. Think about a way how to tell the other program when to release the lock etc. You can use stdin for messenging und use 3 constants or something. In this case it's still rather simple
    • It's bad for performance because you keep creating processes which is expensive.

    Another way would be to start another program that runs all the time. You connect to it using some means of IPC (probably just use a tcp channel because it's cross-platform) and allow this program to manage file acces. That program could be a php script in an endless loop as well, but it will probably be simpler to code this in Java or another language that has multithreading support.

    Another way would be to leverage existing ressources. Create a dummy database table for locks, create an entry for the file and then do table-row-locking.

    Another way would be not to use files, but a database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c