dongmaxi6763 2011-02-05 05: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 05: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部