Is a move operation in Unix atomic?

房东的猫 提交于 2019-11-30 06:47:00

A UNIX rename operation is atomic (see rename(2)). The UNIX mv command uses rename if the source and target path are on the same physical device. If the target path is on a different device, the rename will fail, and mv will copy the file (which is not atomic).

If the target file path exists, the rename will atomically remove it from the file system and replace it with the new file. The file won't actually be deleted until its reference count drops to zero, so if another process is currently reading the file, it will keep reading the old file. Once all processes have closed the old file, its reference count will drop to zero and the file storage space will be reclaimed.

  1. move(rename) is atomic if done on the same device. (device = same disk/partition)
  2. If Foo.txt exits move Foo.tmp to Foo.txt most likely will fail. (But if you first delete Foo.txt and then move, it should work). What happens is that a file is not physically deleted until all file handlers are closed (there is no process that uses that file). Also, after remaining Foo.tmp to Foo.txt you will have 2 Foo.txt files. One that is deleted but still opened in memory (basically that file does not have a reference on disk anymore) and one that actually resides on disk.
  3. But, after move, in second process you need to reopen the file.

Let me know if we are on the same page with #1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!