Golang的OpenFile函数中的O_APPEND标志不会遵守Seek操作。

huangapple go评论94阅读模式
英文:

Golang OpenFile O_APPEND does not respect Seek

问题

当我以这种方式打开文件时:

file, _ := os.OpenFile("/path/to/my/file", os.O_RDWR|os.O_APPEND, os.FileMode(0666))
file.Seek(start, os.SEEK_SET)
io.CopyN(file, resp.Body, length)

io.CopyN不会遵循我寻找的位置。它似乎只是将内容追加到文件的末尾。相反,如果我像这样打开文件:

file, _ := os.OpenFile("/path/to/my/file", os.O_RDWR, os.FileMode(0666))
file.Seek(start, os.SEEK_SET)
io.CopyN(file, resp.Body, length)

它按照我期望的方式工作。io.CopyN从我寻找的"start"点开始向文件写入内容。不确定这是一个特性还是一个错误?

英文:

When I open file in mode like this:

file, _ := os.OpenFile("/path/to/my/file", os.O_RDWR|os.O_APPEND, os.FileMode(0666))
file.Seek(start, os.SEEK_SET)
io.CopyN(file, resp.Body, length)

io.CopyN does not respect the position where I sought. It seems it just append to the tail of the file. Instead if I open the file like this:

file, _ := os.OpenFile("/path/to/my/file", os.O_RDWR, os.FileMode(0666))
file.Seek(start, os.SEEK_SET)
io.CopyN(file, resp.Body, length)

It works as I expected. io.CopyN writes to the file from the "start" point I sought. Not sure if this is a feature or a bug?

答案1

得分: 10

这是一个特性(http://man7.org/linux/man-pages/man2/open.2.html),由底层操作系统控制,而不是由golang运行时控制。

O_APPEND
文件以追加模式打开。在每次写入(write(2))之前,文件偏移量会被定位到文件末尾,就像使用lseek(2)一样。如果多个进程同时向一个文件追加数据,O_APPEND可能会导致NFS文件系统上的文件损坏。这是因为NFS不支持对文件进行追加,所以客户端内核必须模拟追加操作,这样就无法避免竞争条件。

英文:

It's definitely a feature (http://man7.org/linux/man-pages/man2/open.2.html) and it's controlled by underlying OS, not golang runtime.

O_APPEND
          The file is opened in append mode.  Before each write(2), the
          file offset is positioned at the end of the file, as if with
          lseek(2).  O_APPEND may lead to corrupted files on NFS
          filesystems if more than one process appends data to a file at
          once.  This is because NFS does not support appending to a
          file, so the client kernel has to simulate it, which can't be
          done without a race condition.

huangapple
  • 本文由 发表于 2014年2月5日 18:14:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/21574288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定