I read a book about files in Linux, and it gives the next example:
int main(char ** argv, int argc) {
int stat;
int fd = open("dugma1.txt", O_WRONLY, 0666);
if (fork() == 0) {
int fd2 = open("dugma1.txt", O_WRONLY, 0666);
sleep(10);
if (lockf(fd2, F_TLOCK, 17) >= 0) {
write(fd2, "I was here second", 17);
}
} //if
else {
lockf(fd, F_TLOCK, 16);
write(fd, "I was here first", 16);
wait(&stat);
}
}
It says that the output will be:I was here first, and the reason: We don’t close the file. But I didn’t understand this explantion. We first write: I was here first, but why after the sleep(10) we will not go to this part of the code:
if (lockf(fd2, F_TLOCK, 17) >= 0) {
write(fd2, "I was here second", 17);
}
F_TLOCK is a non-blocking, and for that we will succsses writing “I was here second”.
Thanks
The parent executes
lockf(fd, F_TLOCK, 16)on the opened file, locking the first16bytes. Then it writes the text inside and waits for the child to exit. It does not close the file and hence the lock remains. If there was aclose(fd);in the parent’s code after thewrite(), the lock would have been released but there isn’t.The child first sleeps for a while and when it tries to lock the first 17 bytes of the file but that fails since the parent still has the lock. That’s why
lockf(fd2, F_TLOCK, 17)fails withEAGAIN– the operation should be repeated later on. Errors are signalled by a return value of-1which makes the conditional in the child code not to execute.