检查IPC共享锁 [英] Checking IPC Shareable lock

查看:65
本文介绍了检查IPC共享锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在perl中使用IPC :: Shareable时,如何检查别人是否持有锁. 我有以下代码:

How can I check if a lock is held by someone else while using IPC::Shareable in perl. I have the below code:

my $resource = 0;
my $resource_handle = tie  $resource, 'IPC::Shareable', undef , { destroy => 1 };

my $child = fork;
unless ($child) {
    $resource_handle -> shlock();
    sleep 10;
    $resource_handle -> shunlock();
    exit(0);
}
sleep 2;
if ($resource_handle -> shlock(LOCK_EX)) {
    print "Got lock in parent\n";
    $resource_handle -> shunlock();
} else {
    print "The shared resource is locked\n";
}

当我希望它打印共享资源已锁定"时,这会在10秒后打印父级锁定".

This prints "Got lock in parent" after 10 seconds while I want it to print "The shared resource is locked".

推荐答案

您要执行非阻塞锁定.锁定呼叫将立即返回.如果锁可用,则锁调用的返回值将为true,您将已获取该锁.如果返回值为false,则说明其他资源拥有该资源.

You want to do a non-blocking lock. The lock call will return right away. If the lock was available, the return value of the lock call will be true and you will have acquired the lock. If the return value is false, then something else possesses the resource.

if ($resource_handle -> shlock(LOCK_EX | LOCK_NB)) {
    print "Got lock in parent\n";
    $resource_handle -> shunlock();
} else {
    print "The shared resource is locked\n";
}

这篇关于检查IPC共享锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆