在 golang 中,移动打开的文件会导致泄漏或任何其他问题吗?
In golang, does moving an open file cause a leak or any other problem?
考虑以下代码:
f, err := os.Create(tmpFilepath)
defer f.Close()
// do some writing to f
os.Rename(tmpFilepath, newpath)
一些错误处理已被删除以简化。
此外,我知道这段代码是错误的,但我想了解这段代码在文件正确性和性能方面的影响。
这里有资源泄漏吗?
顺便说一下,修复是在您完成写入文件后关闭。
如果我们正在讨论 OS 和实现 POSIX 语义的文件系统(也就是说,不是 Windows 通常不允许您重命名打开的文件) , 绝对没有问题:打开的文件描述符仅算作文件数据的硬链接。
重命名文件的数据不会以某种方式与打开的文件描述符分离——将后者视为对该数据的一种 "anonymous" 引用。
If the link count of the file is 0, when all file descriptors associated with the file are closed, the space occupied by the file shall be freed and the file shall no longer be accessible.
考虑以下代码:
f, err := os.Create(tmpFilepath)
defer f.Close()
// do some writing to f
os.Rename(tmpFilepath, newpath)
一些错误处理已被删除以简化。
此外,我知道这段代码是错误的,但我想了解这段代码在文件正确性和性能方面的影响。
这里有资源泄漏吗?
顺便说一下,修复是在您完成写入文件后关闭。
如果我们正在讨论 OS 和实现 POSIX 语义的文件系统(也就是说,不是 Windows 通常不允许您重命名打开的文件) , 绝对没有问题:打开的文件描述符仅算作文件数据的硬链接。
重命名文件的数据不会以某种方式与打开的文件描述符分离——将后者视为对该数据的一种 "anonymous" 引用。
If the link count of the file is 0, when all file descriptors associated with the file are closed, the space occupied by the file shall be freed and the file shall no longer be accessible.