• 技术文章 >php教程 >php手册

    php使用多个进程同时控制文件读写示例

    2016-06-13 09:41:43原创411

    复制代码 代码如下:


    /**
    * 写入数据
    * @param [string] $path [文件路径]
    * @param [string] $mode [文件打开模式]
    * @param [string] $data [数据]
    * @return [bool]
    */
    function writeData($path, $mode, $data){
    $fp = fopen($path, $mode);
    $retries = 0;
    $max_retries = 100;
    do {
    if ($retries > 0) {
    usleep(rand(1, 10000));
    }
    $retries += 1;
    }while (!flock($fp, LOCK_EX) and $retries <= $max_retries);
    if ($retries == $max_retries) {
    return false;
    }
    fwrite($fp, $data."\r\n");
    flock($fp, LOCK_UN);
    fclose($fp);
    return true;
    }


    /**
    * 读数据
    * @param [string] $path [文件路径]
    * @param [string] $mode [文件打开模式]
    * @return string
    */
    function readData($path,$mode){
    $fp = fopen($path, $mode);
    $retries = 0;
    $max_retries = 100;
    do {
    if ($retries > 0) {
    usleep(rand(1, 10000));
    }
    $retries += 1;
    }while (!flock($fp, LOCK_SH) and $retries <= $max_retries);
    if ($retries == $max_retries) {
    return false;
    }
    $contents = "";
    while (!feof($fp)) {
    $contents .= fread($fp, 8192);
    }
    flock($fp, LOCK_UN);
    fclose($fp);
    return $contents;
    }

    writeData('D:/webServer/demo.txt','a+','this is a demo');
    echo readData('D:/webServer','r+');

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:php 进程 文件
    上一篇:PHP数据过滤函数 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • php mysql 数据库类• PHP代码:Http断点续传的实现例子• 基于php实现七牛抓取远程图片• php5.3,5.4,5.5,5.6 中新特性• ThinkPHP控制器里javascript代码不能执行的解决方法,thinkphpjavascript
    1/1

    PHP中文网