使用flock的PHP问题-文件锁定 [英] PHP issues using flock - file locking

查看:183
本文介绍了使用flock的PHP问题-文件锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用PHP flock() 函数时遇到问题.我需要编写两个不同的变量($O$o),但是通常它不写第二个变量($o),这可能是因为文件连续写了两次.

I'm having a problem using the PHP flock() function. I need to write two different variables ($O and $o) but often it doesn't write the second variable ($o), maybe because the file is written two times in a row.

代码如下:

include_once "changevar.php";
changevar("O",$seguimedia,$filename,0);
changevar("o",$offerta,$filename,0);

正确设置了

$seguimedia$filename$offerta.

changevar.php:

changevar.php:

function changevar($varname,$newval,$filename,$type)
{
    while(!$fp=fopen($filename,"c+"))
    {
        usleep(100000);
    }
    while(!flock($fp,LOCK_EX))
    {
        usleep(100000);
    }
    while(!include($filename))
    {
        usleep(100000);
    }
    ftruncate($fp,0);
    rewind($fp);
    $$varname=$newval;
    if($type==0)
    {
        foreach(array("u","p","t","d") as $v){$$v=str_replace("\\","\\\\",$$v);}
        $text="<?\$o=$o;\$u=\"$u\";\$c=$c;\$m=$m;\$p=\"$p\";\$C=$C;\$id=\"$id\";\$t=\"$t\";\$d=\"$d\";\$O=$O;?>";
    }
    else
    {
        $text="<?\$impressions=$impressions;\$clickunici=$clickunici;\$clicknulli=$clicknulli;\$creditiguadagnati=$creditiguadagnati;\$creditiacquistati=$creditiacquistati;\$creditiutilizzati=$creditiutilizzati;?>";
    }
    fwrite($fp,$text);
    flock($fp,LOCK_UN);
    fclose($fp);
}

PHP flock()是避免此类问题的好方法吗?
我需要使用哪种语言/功能?

Is PHP flock() a good way to avoid this kind of problems?
Which language/functions do I need to use?

推荐答案

问题实际上出在fopen()调用中.

The problem is actually in the fopen() call.

您正在以c+模式打开文件.这意味着文件指针位于文件的开头,这将导致任何写操作都覆盖已存在的内容. 为了增加侮辱性伤害,您正在调用ftruncate(),在写入之前将文件截断为0字节-因此,在每次写入之前,您都在手动擦除整个文件.因此,该代码保证,仅保留对文件的最后一次写操作,并手动进行擦除操作.

You're opening the file in mode c+. This means that the file pointer is located at the beginning of the file, which would cause any write to overwrite what's already there. To add insult to injury, you're calling ftruncate(), truncating the file to 0 bytes right before writing -- therefore, before every write, you're manually erasing the whole file. That code is, thus, guaranteeing that only the last write to the file will remain, manually taking care of erasing every single other one.

fopen()调用应使用模式a+进行,并且ftruncate()rewind()都需要执行(后者也具有将文件指针放在开头的作用).

The fopen() call should be made with mode a+, and both ftruncate() and rewind() need to go (the latter also having the effect of putting the file pointer at the beginning).

这篇关于使用flock的PHP问题-文件锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆