/* * 文件的锁定机制 * flock()轻便的咨询文件锁定 * LOCK_SH取得共享锁定(读取的程序)。  * LOCK_EX 取得独占锁定(写入的程序。  * LOCK_UN 释放锁定(无论共享或独占)。  * 如果不希望 flock() 在锁定时堵塞,则是 LOCK_NB(Windows 上还不支持)。  *   */ /*  * 留言板  */    $filename = "message.txt";    if(isset($_POST['dosubmit'])){        //字段的分隔||  行的分隔[n]        $mess = "{$_POST['username']}||".time()."||{$_POST['title']}||{$_POST['content']}[n]";        writemessage($filename, $mess);    }    if(file_exists($filename)){        readmessage($filename);    }    //读信息    function readmessage($filename){          //      $mess = file_get_contents($filename);                $mess = "";                $fp = fopen($filename, "r");                flock($fp, LOCK_SH+LOCK_NB);//读锁定                while(!feof($fp)){                    $mess .=fread($fp, 1024);                }                flock($fp, LOCK_UN+LOCK_NB);//释放锁                $mess = rtrim($mess,"[n]");                $arrmess = explode("[n]", $mess);                foreach($arrmess as $m){                    list($username,$daytime,$title,$content) = explode("||", $m);                    echo "{$username},".date('Y-m-d H:i:s',$daytime).",{$title}
{$content}
";                }                fclose($fp);    }    //写信息    function writemessage($filename,$mess){        $fp = fopen($filename, "a");       //锁定文件        if(flock($fp, LOCK_EX+LOCK_NB)){            fwrite($fp, $mess);            flock($fp,LOCK_UN+LOCK_NB);//释放文件        }else{            echo '写入锁定失败!';        }        fclose($fp);    }?>
用户名:
标题:
内容: