0

Platform: ubuntu 14.4

gcc version: 4.8.2

Language: C

Situation:

I have two files to test the function of lockf.One is to write and the other is to read.

During write target file should be locked, thus disabling the read to open the same file.

Problem:

When I run the write program, I just leave it waiting for user input and start the read program. Somehow the read is able to get the information in the target file. Meaning that the lockf in write is not locking it correctly. Why am I failing?

Code:

read.c

int main()
{
    char buffer[4];
    char *filename = "/home/fikrie/Documents/test_lockf/file.txt";
    int fd;

    fd = open(filename, O_RDONLY, 0644);
    lockf(fd, F_LOCK, 3);
    while (1) {
            if (read(fd, buffer, 3) == -1) {
                    printf("Error getting file");
                    break;
            } else {
                    printf("%s",buffer);
                    getchar();
            }
    }
    close(fd);
    lockf(fd, F_ULOCK, 0);

    return 0;
}

write.c

int main()
{
    char buffer;
    char *filename = "/home/fikrie/Documents/test_lockf/file.txt";
    int fd;

    fd = open(filename, O_WRONLY | O_APPEND, 0644);
    lockf(fd, F_LOCK, 3);
    while(1) {
            buffer = getchar();
            if (buffer != 'q') {
                    write(fd,"ABC",3);
                    write(fd,":",1);
            }
            else {
                    break;
            }
    }
    close(fd);
    lockf(fd, F_ULOCK, 0);

    return 0;
}

etc:

From the man page,

lockf(int fd, int function, off_t size);

size argument is the number of contiguous bytes to be locked or unlocked. The section to be locked or unlocked starts at the current offset in the file and extends forward for a positive size or backward for a negative size.

I thought I passed wrong value for size arguments, so I tried passing 0 as well. But the results are just same.

Rajesh
  • 356
  • 1
  • 5
  • 15
Mohd Fikrie
  • 197
  • 4
  • 21
  • 2
    Are you sure `lockf()` succeeds? You're ignoring its return value which is generally a bad idea. Also, why are you calling `open()` with three arguments in `O_RDONLY` mode? That's not right. You should check that `open()` succeeds too, before assuming it did. – unwind Mar 05 '15 at 08:54
  • @unwind. you are right. I was assuming too early without checking the return value of lockf. Thanks for the guide. The return value in read is -1. Which is correct. I was assuming it because I got the value inside the file. Sorry for my mistake. – Mohd Fikrie Mar 05 '15 at 09:13

1 Answers1

1

The Lockf command requires the file descriptor to be writeable for the F_LOCK version to succeed.

From the manual page:

ERRORS
EBADF fd is not an open file descriptor; or cmd is F_LOCK or F_TLOCK and fd is not a writable file descriptor.

PS: @unwind, exactly right, check the error codes.

user3710044
  • 2,261
  • 15
  • 15