1

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".

Vivek
  • 2,000
  • 3
  • 16
  • 22

2 Answers2

3

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";
}
mob
  • 117,087
  • 18
  • 149
  • 283
  • Can you please explain a bit more. This did work. How is "LOCK_EX | LOCK_NB" different from just "LOCK_EX" – Vivek Nov 17 '11 at 17:11
  • `LOCK_NB` is "non-blocking". If the lock isn't available, the lock call returns false immediately. Without this, the lock call "blocks" - waits until the lock is available before returning. – mob Nov 17 '11 at 17:19
0

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.

Axeman
  • 29,660
  • 2
  • 47
  • 102
  • Sorry, that was a mistake , I forgot the sleep in parent, edited it now. This still gives me the same results. – Vivek Nov 17 '11 at 17:07