「php入門」phpで複数のプロセスを制御して同時に一つのファイルを書き込む

phpコード:

<?php

/**
* データを書き込み
* @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_startnews24.txt’,’a+’,’これはデモプログラム’);
echo readData('D:/webServer’,’r+’);

PHP

Posted by arkgame