简体   繁体   中英

Can you safely read a file which is target of mv command?

I have heard that the mv command in linux is atomic. But does that mean we can safely read the file? Will we always see the content after the mv command is completed?

I have the following scenario. I have different processes responsible for writing and reading a file. I have one process that is periodically running mv a.txt b.txt and another process that is periodically running cat b.txt . My question is, will cat b.txt always avoid seeing partial file content? Ie will it always see the content of b.txt before or after the mv command (and not in between the write)? I think many os uses separate key for read and write, so I am not sure if this process ( mv in parallel with cat ) is safe.

My other question is - if it is not safe to run mv and cat in parallel, then what can I do to ensure safety? Will I need to explicitly use lock the file myself (using fcntl or something else)?

It is safe to call mv and cat at the same time, and cat will always see the content of b.txt before or after mv .

mv uses the rename(2) system call :

The mv utility shall perform actions equivalent to the rename() function [...]

rename(2) guarantees atomicity:

If the link named by the new argument exists, it shall be removed and old renamed to new. In this case, a link named new shall remain visible to other threads throughout the renaming operation and refer either to the file referred to by new or old before the operation.

That specification requires that the action of the function be atomic.

It's made atomic by this guarantee from cat 's open(2) call:

The open() function shall establish the connection between a file and a file descriptor

Namely, once the connection has been established, cat won't see another file. POSIX doesn't guarantee that reads of a file that has been renamed won't fail, but in practice, POSIX implementations including Linux won't fail the read.

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