简体   繁体   中英

Linux/ File in linux and F_TLOCK issue

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

lockf(fd2,F_TLOCK,17)

Encounters an error (EAGAIN) and therefore returns -1. The value required to write to the file is equal to or greater than 0, not -1. The test fails and the write never occurs.

The parent executes lockf(fd, F_TLOCK, 16) on the opened file, locking the first 16 bytes. 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 a close(fd); in the parent's code after the write() , 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 with EAGAIN - the operation should be repeated later on. Errors are signalled by a return value of -1 which makes the conditional in the child code not to execute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM