Advisory Locking With fcntl()

Has anyone successfully used fcntl() to lock a file?
The following code open’s and locks a file
then checks to see if it is locked, but
fl.l_pid is never assigned. Whats wrong
with this code.

// open and lock the file
fd = creat( “/fs/fd/test.txt”, O_WRONLY );
flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0; // until EOF
int iRet = fcntl(fd,F_SETLK,&fl);

// open another file desc. and check for lock
fd2 = creat( “/fs/fd/test.txt”, O_WRONLY );
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0; // until EOF
fl.l_pid = -1;
iRet = fcntl(fd2,F_GETLK,&fl);

close(fd);
close(fd2);

mixalhs <mkonstan@watfast.uwaterloo.ca> wrote:

Has anyone successfully used fcntl() to lock a file?
The following code open’s and locks a file
then checks to see if it is locked, but
fl.l_pid is never assigned. Whats wrong
with this code.

Advisory locking is used between processes, not between
file descriptors so you won’t every have a conflict
there. Running your code with some slight modifications
(clear the lock structures before you use them and don’t
set the pid field) you get the results you would expect
if you run the test as two processes.

Thomas


#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>

#define FILE_NAME “newfile”

int main(int argc, char **argv) {
flock_t fl;
int fd, fd2, iRet;

#if defined(SET_LOCK)
// open and lock the file
if((fd = creat( FILE_NAME, O_WRONLY )) == -1) {
perror(“Can’t open file”);
return 0;
}
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0; // until EOF
if ((iRet = fcntl(fd,F_SETLK,&fl)) == -1) {
perror(“First lock failed \n”);
return 0;
}
#endif

#if defined(GET_LOCK)
// open another file desc. and check for lock
if((fd2 = open( FILE_NAME, O_WRONLY )) == -1) {
perror(“Can’t open file”);
return 0;
}
memset(&fl, 0, sizeof(fl));
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0; // until EOF
if((iRet = fcntl(fd2,F_GETLK,&fl)) == -1) {
perror(“Second lock failed \n”);
return 0;
}
printf(“pid %d has lock from %d-%d type %d \n”,
fl.l_pid,
fl.l_start,
fl.l_start + fl.l_len,
fl.l_type);
#endif

//Give us some time to run the other process
sleep(30);

close(fd);
close(fd2);

return 0;
}