浅谈Linux下mv和cp命令的区别--转载

我以前在项目中遇到一个很奇怪的问题,对于inotify监视一个文件的时候,发现有些时候inotify有些时候会node

“失效”。后来我就没办法,去监视文件所在的目录。看下面的,python

[python] view plaincopyprint?
  #!/bin/bash  

  src=/tmp/test/test.txt      # directory to monitor  
  /usr/local/bin/inotifywait -rmq  -e modify $src |  while read  event  
  do  
      echo "hello"  
  done

奇怪的现象就是若是我 mv test.txt /tmp/test/test.txt 的时候,发现 inotify 居然没有除非,可是我无心中
发现 cp test.txt /tmp/test/test.txt 的时候,强制覆盖了,发现 inotity 就触发了。我这两天上OS的时候,突bash

然间想到了缘由。多是 inode 节点的问题,看下面code

上面注意 inode 节点的变化,cp 的时候是真正意义上的内容copy,对于 inode 节点倒是不会变化的内存

mv 的时候是把目标文件直接删除了(inode 删除了),新的文件其实已经不是之前的文件了,只是名字string

同样而已。这样就能够解释 inotify 的“异常”了,mv 以后原文件的 inode 节点都已经删除了,inotify是跑it

在内存里面的,它依然在读取以前的 inode 节点,可是已经删除了,这致使了inotify挂了。io

inode 是OS在磁盘上寻找文件一个必不可少的,下面能够再来看个例子.event

[python] view plaincopyprint?
  #include <stdio.h>  
  #include <string.h>  
  #include <stdlib.h>  
  #include <fcntl.h>  

  int main(int argc, char const *argv[])  
  {  
      /* code */  
      int fd = open("./1.txt",O_RDWR);  
      char buff[256] = {'\0'};  
      if (fd < 0)  
      {  
          printf("error open file\n");  
          exit(1);  
      }  
      int i = 0;  
      while(1)  
      {  
          sprintf(buff,"%d %s\n",i,"hello");  
          write(fd,buff,strlen(buff)+1);  
          printf("%s\n",buff );  
          ++i;  
          sleep(1);  
      }  
      close(fd);  
      return 0;  
  }

上面的程序就是向1.txt写文件,前提是 1.txt 是存在的,真正的缘由就是没有 inode 节点,也就没有了对应test

的磁盘文件.如今假设有了 1.txt 这时候程序 1s 钟写一次文件,咱们 mv 1.txt 2.txt ,这时候会发现程序竟

然向 2.txt 里面写数据了,缘由就是程序是在内存里面,对于1.txt 的抽象就是文件描述符号,write只认识它

,write 经过写描述符,描述符去找相应的 inode 节点,而后写磁盘.mv 了以后 inode 节点仍是存在的,也

就是写 2.txt 了.

相关文章
相关标签/搜索