Nov 7, 2015

PHPでの排他制御、ロックファイル版

PHPスクリプトで排他制御を行う方法には、セマフォ、sem_get, sem_acquire, sem_release 関数を使う方法があるが、PHPのビルドで、 '--enable-sysvsem' オプションが必要になる。

(If we want to use an exclusive control in PHP script, we can use semaphore functions, sem_get, sem_acquire, and sem_release, but there must be an '--enable-sysvsem' option while building PHP.)

レンタルサーバー側で、このオプションがないときは、sem_get関数等が動作しなくなる。

(When there is not an '--enable-sysvsem' option on your rental server, sem_get will abort immediately.)

対応策は、排他制御の目的だけのロックファイルを用意する方法である。

(To correspond this, we can use a lock-file-method only for the purpose of an exclusive control.)

ロックファイルは、初めから存在する必要もないので手間がいらないが、作り捨てのままとなる
。

(A lock file should not be prepared before running your script, but there is always the lock file in the following example.)

ロックファイル名は、".ht"で始めるとWEBアクセスされることがない。

(It is better that the name of a lock file begins ".ht", because it will not be accessed from any WEB clients.)

コード例 (example)

$seg = fopen(".htlockfile", "w");
if($seg){
 flock($seg, LOCK_EX);
 //ここが排他区間となり、排他処理を記入する
 //(Here is an exclusive control span.)
 flock($seg, LOCK_UN);
 fclose($seg);
}



No comments:

Post a Comment