使用Windows/NTFS附加到原子文件吗? [英] Is appending to a file atomic with Windows/NTFS?

查看:77
本文介绍了使用Windows/NTFS附加到原子文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要从多个进程中编写一个简单的文本日志文件,它们是否会覆盖/破坏彼此的条目?

If I'm writing a simple text log file from multiple processes, can they overwrite/corrupt each other's entries?

(基本上,这个问题在UNIX中文件附加原子吗?但是Windows/NTFS.)

(Basically, this question Is file append atomic in UNIX? but for Windows/NTFS.)

推荐答案

即使append是原子的(我不相信这是原子的),它也可能不会为您提供所需的结果.例如,假设日志包含时间戳记,则可以预期在较旧的日志之后附加更多的最新日志,这似乎是合理的.对于并发,这种保证不成立-如果多个进程正在等待写入同一文件,则其中任何一个都可能会获得写锁-而不仅仅是等待最久的一个.因此,日志可以不按顺序写入.

Even if append is atomic (which I don't believe it is), it may not give you the results you want. For example, assuming a log includes a timestamp, it seems reasonable to expect more recent logs to be appended after older logs. With concurrency, this guarantee doesn't hold - if multiple processes are waiting to write to the same file, any one of them might get the write lock - not just the oldest one waiting. Thus, logs can be written out of sequence.

如果这不是理想的行为,则可以通过将所有进程的日志条目发布到共享队列(例如命名管道)来避免这种情况.然后,您将有一个从该队列写入日志文件的进程.这样可以避免并发性问题,确保按顺序写入日志,并且在文件附加不是原子的情况下也可以工作,因为文件只能由一个进程直接写入.

If this is not desirable behaviour, you can avoid it by publishing logs entries from all processes to a shared queue, such as a named pipe. You then have a single process that writes from this queue to the log file. This avoids the conccurrency issues, ensures that logs are written in order, and works when file appends are not atomic, since the file is only written to directly by one process.

这篇关于使用Windows/NTFS附加到原子文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆