I have a C program that uses fcntl() to lock files, the following code is a test program that does a lock, sleep, unlock:
#include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> int main() { struct flock lock; int fd; fd = open("a",O_WRONLY); lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 1; lock.l_pid = 0; printf("%d\n",fcntl(fd, F_SETLKW, &lock)); sleep(20); lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 1; lock.l_pid = 0; printf("%d\n",fcntl(fd, F_SETLKW, &lock)); close(fd); return(0); }
I would like to write a perl script to do the same locking so I wrote:
!/usr/bin/perl use strict; use Fcntl; my($pack); open(FILE,">a"); $pack = pack('s s l l l', &F_WRLCK, 0, 0, 1, 0); print(fcntl(FILE, &F_SETLKW, $pack) . "\n"); sleep(20); $pack = pack('s s l l l', &F_UNLCK, 0, 0, 1, 0); print(fcntl(FILE, &F_SETLKW, $pack) . "\n"); close(FILE);
The two programs when run right after one another dont see each other's lock, but when running two copies of the same program (either program) they respect the lock. I imagine I have the perl syntax not quite matched up to the C syntax. Any help would be appriciated.

In reply to fcntl() madness with C and perl by darkomen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.