Advisory File 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 wrote:

Has anyone successfully used fcntl() to lock a file?

As far as I know, it works.

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.

You have a bug in your creat() call.

// open and lock the file
fd = creat( “/fs/fd/test.txt”, O_WRONLY );

This should not be O_WRONLY, it should be a file permission/mode.
O_WRONLY == 1 == S_IXOTH … your file is created with only
execute-other permissions, so your second creat() call should
fail (unless you’re root) with EACCES.

// open another file desc. and check for lock
fd2 = creat( “/fs/fd/test.txt”, O_WRONLY );

Checking the return code of all system calls is good practice.