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.