简体   繁体   English

Linux / Linux中的文件和F_TLOCK问题

[英]Linux/ File in linux and F_TLOCK issue

I read a book about files in Linux, and it gives the next example: 我读了一本关于Linux中文件的书,它给出了下一个示例:

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. 它说输出将是: I was here first ,原因是:我们没有关闭文件。 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: 我们首先写: I was here first ,但是为什么在sleep(10)我们不去看代码的这一部分:

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". F_TLOCK是非阻塞的,为此,我们将成功编写“我在这里第二”。

Thanks 谢谢

lockf(fd2,F_TLOCK,17)

Encounters an error (EAGAIN) and therefore returns -1. 遇到错误(EAGAIN),因此返回-1。 The value required to write to the file is equal to or greater than 0, not -1. 写入文件所需的值等于或大于0,而不是-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. 父级对打开的文件执行lockf(fd, F_TLOCK, 16) ,锁定前16个字节。 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); 如果close(fd); in the parent's code after the write() , the lock would have been released but there isn't. write()之后的父代代码中,该锁将被释放,但没有释放。

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. 子级先休眠一段时间,然后尝试锁定文件的前17个字节,但这失败了,因为父级仍具有该锁定。 That's why lockf(fd2, F_TLOCK, 17) fails with EAGAIN - the operation should be repeated later on. 这就是为什么lockf(fd2, F_TLOCK, 17)失败并显示EAGAIN -稍后应重复该操作。 Errors are signalled by a return value of -1 which makes the conditional in the child code not to execute. 错误由返回值-1表示,该值使子代码中的条件条件不执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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