简体   繁体   English

何时在Go中刷新文件?

[英]When to flush a file in Go?

When is it necessary to flush a file? 什么时候需要刷新文件?
I never do it because I call File.Close and I think that it is flushed automatically, isn't it? 我从来没有这样做因为我调用File.Close并且我认为它是自动刷新的,不是吗?

See here . 看到这里 File.Sync() is syscall to fsync . File.Sync()是对fsync的系统调用 You should be able to find more under that name. 您应该能够在该名称下找到更多。

Keep in mind that fsync is not the same as fflush and is not executed before close. 请记住, fsyncfflush不同,并且在关闭之前不会执行。

You generally don't need to call it. 您通常不需要调用它。 The file will be written to disk anyway, after some time and if there is no power failure during this period. 无论如何,在一段时间之后,如果在此期间没有电源故障,该文件将被写入磁盘。

You'll notice that an os.File doesn't have a .Flush() because it doesn't need one because it isn't buffered. 您会注意到os.File没有.Flush(),因为它不需要缓存,因为它没有缓冲。 Writes to it are direct syscalls to write to the file. 写入它是直接系统调用来写入文件。

When your program exits(even if it crashes) all files it has open will be closed automatically by the operating system and the file system will write your changes to disk when it gets around to it (sometimes up to few minutes after your program exits). 当您的程序退出时(即使它崩溃),它打开的所有文件都将由操作系统自动关闭,文件系统会在更改时将更改写入磁盘(有时在程序退出后几分钟) 。

Calling os.File.Sync() will call the fsync() syscall which will force the file system to flush it's buffers to disk. 调用os.File.Sync()将调用fsync()系统调用,这将强制文件系统将其缓冲区刷新到磁盘。 This will guarantee that your data is on disk and persistent even if the system is powered down or the operating system crashes. 即使系统断电或操作系统崩溃,这也可以保证您的数据在磁盘上并且是持久的。

You don't need to call .Sync() 你不需要调用.Sync()

Looks the most recommendations here are to not to call fsync(), but in general it mainly depends on your application requirement. 看起来这里最多的建议是不要调用fsync(),但一般来说它主要取决于你的应用程序要求。 If you are working on critical file read/write, its always recommended to call fsync(). 如果您正在处理关键文件读/写,则始终建议调用fsync()。

http://www.microhowto.info/howto/atomically_rewrite_the_content_of_a_file.html#idp31936 http://www.microhowto.info/howto/atomically_rewrite_the_content_of_a_file.html#idp31936

link, has more details on when file.Sync() will help. 链接,有关file.Sync()何时有用的更多详细信息。

When you want to ensure data integrity as much as possible. 当您想要尽可能确保数据完整性时。 For example, what happens if your program crashes before it comes to closing the file? 例如,如果您的程序在关闭文件之前崩溃会发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM