Che*_*eng 3 perl semaphore ipc
我有一个在mod_perl下执行的Perl CGI程序。在该程序中,我想防止资源同时被多个进程访问。
# Semaphore Initialization Code
# 10023 is unique id, and this id will be same across different apache process.
# 1, Only one semaphore being created.
# 0722, as all process will be execute under apache account. Hence, they will all having '7' privilege.
my $sem = new IPC::Semaphore(10023, 1, 0722 | IPC_CREAT); # Code(1)
# Set 0th (one and only one) semaphore's value to 1, As I want to use this semaphore as mutex.
$sem->setval(0, 1); # Code(2)
Run Code Online (Sandbox Code Playgroud)
问题是 :
另一种方法是创建一个用于锁定目的的空文件。但是,这最终将具有数千个临时文件。 连结文字
添加IPC_EXCL标志会导致底层semget创建新的信号量或失败。您可以使用它来获得想要的效果。
这应该为您工作:
#Attempt to create (but not get existing) semaphore
my $sem = IPC::Semaphore->new(10023, 1, 0722 | IPC_CREAT | IPC_EXCL);
if ($sem) {
#success, semaphore created, proceed to set.
print "new semaphore\n";
$sem->setval(0, 1);
}
else {
#obtain the semaphore normally
print "existing semaphore\n";
$sem = IPC::Semaphore->new(10023, 1, 0722); #no IPC_CREAT here
die "could not obtain semaphore?" unless $sem;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4026 次 |
| 最近记录: |