Checking IPC Shareable lock

青春壹個敷衍的年華 提交于 2019-12-08 08:12:44

问题


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";
}

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


回答1:


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";
}



回答2:


From what I can see, you have a race condition. You assume that the child will lock the resource before the parent checks the handle. With the code you gave, this indicates no more than the exec after the fork is taking the child process longer than it takes the parent process to branch on 0. (And that seems sensible to me.) Unless you force a sleep in the parent, I don't see that your code and your results indicate any problem.



来源:https://stackoverflow.com/questions/8166063/checking-ipc-shareable-lock

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!