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.