【Perl】ファイルロック(排他処理)について語ろうat PHP
【Perl】ファイルロック(排他処理)について語ろう - 暇つぶし2ch32:nobodyさん
02/06/24 13:52
Perlメモのロック処理をクラスで包んでみた。
特徴
・むちゃくちゃ遅い
・アンロックし忘れがない
・処理全体をロックする場合に便利
・どの環境でも使用できる

#Lock.pm
package Lock;
use strict;
use File::Spec;

sub new{
my($class, %opt) = @_;
my %lfh = (
dir => ($opt{lockdir} || $opt{dir} || 'lock'),
file => ($opt{lockfile} || $opt{file} || 'lockfile'),
timeout => ($opt{timeout} || 60),
trytime => ($opt{trytime} || 10),
);
$lfh{path} = File::Spec->catfile($lfh{dir}, $lfh{file});
for(my $i = 0; $i < $lfh{trytime}; $i++, sleep(1))
{
return bless \%lfh => $class if(rename($lfh{path}, $lfh{current} = $lfh{path} . time));
}
local *LOCKDIR;
opendir(LOCKDIR, $lfh{dir}) or return undef;
while(my $file = readdir(LOCKDIR)){
if ($file =~ /^$lfh{file}(\d+)/){
return bless \%lfh => $class if (time - $1 > $lfh{timeout}
and rename(File::Spec->catfile($lfh{dir}, $file) => $lfh{current} = $lfh{path} . time));
last;
}
}
closedir LOCKDIR;
return undef;
}
sub DESTROY{ rename $_[0]->{current} => $_[0]->{path};}
1;
__END__


次ページ
続きを表示
1を表示
最新レス表示
レスジャンプ
類似スレ一覧
スレッドの検索
話題のニュース
おまかせリスト
オプション
しおりを挟む
スレッドに書込
スレッドの一覧
暇つぶし2ch