[英]Can you safely read a file which is target of mv command?
I have heard that the mv command in linux is atomic.我听说 linux 中的 mv 命令是原子的。 But does that mean we can safely read the file?但这是否意味着我们可以安全地读取文件? Will we always see the content after the mv command is completed? mv命令完成后我们会一直看到内容吗?
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
.我有一个定期运行mv a.txt b.txt
的进程和另一个定期运行cat b.txt
的进程。 My question is, will cat b.txt
always avoid seeing partial file content?我的问题是, cat b.txt
总是避免看到部分文件内容? Ie will it always see the content of b.txt before or after the mv
command (and not in between the write)?即它是否总是会在mv
命令之前或之后看到 b.txt 的内容(而不是在写入之间)? 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.我认为许多操作系统使用单独的密钥进行读写,所以我不确定这个过程( mv
与cat
并行)是否安全。
My other question is - if it is not safe to run mv
and cat
in parallel, then what can I do to ensure safety?我的另一个问题是 - 如果并行运行mv
和cat
不安全,那么我该怎么做才能确保安全? Will I need to explicitly use lock the file myself (using fcntl or something else)?我是否需要自己明确使用锁定文件(使用 fcntl 或其他东西)?
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
和cat
是安全的, cat
总是会看到mv
之前或之后的b.txt
的内容。
mv
uses the rename(2)
system call : mv
使用rename(2)
系统调用:
The mv utility shall perform actions equivalent to the rename() function [...] mv 实用程序应执行与 rename() 函数等效的操作 [...]
rename(2)
guarantees atomicity: rename(2)
保证原子性:
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.在这种情况下,一个名为 new 的链接在整个重命名操作期间对其他线程保持可见,并且在操作之前引用 new 或 old 引用的文件。
That specification requires that the action of the function be atomic.该规范要求函数的操作是原子的。
It's made atomic by this guarantee from cat
's open(2)
call:通过cat
的open(2)
调用的这种保证,它变得原子化:
The open() function shall establish the connection between a file and a file descriptor open() 函数应建立文件和文件描述符之间的连接
Namely, once the connection has been established, cat
won't see another file.也就是说,一旦建立了连接, cat
就不会再看到另一个文件了。 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. POSIX 不保证读取已重命名的文件不会失败,但实际上,包括 Linux 在内的 POSIX 实现不会导致读取失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.