douzhanyan5015 2013-03-08 23:49
浏览 50
已采纳

如何在PHP中使用flock? [关闭]

In my php code, I want to create a reader/writer code. So there will be a file that the php code wither reads or writes to. There can only be 1 writer, or there can be many readers, but you can write and read at the same time.

How can this be done in PHP? I believe you need to use the flock code?

  • 写回答

2条回答 默认 最新

  • dongwen3410 2013-03-08 23:54
    关注

    I'm with Danack's comment - the php documentation of flock() contains a very good example:

    $fp = fopen("/tmp/lock.txt", "r+");
    
    if (flock($fp, LOCK_EX)) { // exclusive lock will blocking wait until obtained
    
        fwrite($fp, "Write something here
    ");
    
        // or ...
    
        execute_code_that_shouldnt_run_twice_at_the_same_time();
    
        flock($fp, LOCK_UN); // unlock
    } else {
        echo "failed to obtain lock";
    }
    
    fclose($fp);
    

    Note that flock() in default mode will blocking wait until it can obtain the lock. This is regulary the case if the other process obtains the lock currently.


    But don't expect too much from the flock() function. It is using so called advisory locks, which can be ignored by other processes. On Linux for example PHP's flock() is using the kernel function flock(), man 2 flock explains how it works:

    flock() places advisory locks only; given suitable permissions on a file, a process is free to ignore the use of flock() and perform I/O on the file.

    Meaning flock() will just give an advice to other processes. If they don't care about they can read or even write regardless of the lock ( or type of lock). However the man pages are about Linux other system may handle this differently. (It's not the case actually)

    But, however as you are the coder of the processes you can / and should care about the lock using flock() every time you access the file. But you cannot be sure that another process - like a text editor - will not overwrite your file

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

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳