gpt4 book ai didi

go - 在 golang 中,移动打开的文件会导致泄漏或任何其他问题吗?

转载 作者:IT王子 更新时间:2023-10-29 01:56:44 25 4
gpt4 key购买 nike

考虑以下代码:

f, err := os.Create(tmpFilepath)
defer f.Close()
// do some writing to f
os.Rename(tmpFilepath, newpath)

一些错误处理已被删除以简化。

此外,我知道这段代码是错误的,但我试图了解这段代码在文件正确性和性能方面的影响。

这里有资源泄漏吗?

顺便说一句,修复是在您完成写入文件后关闭。

最佳答案

如果我们正在讨论一个实现 POSIX 语义的操作系统和文件系统(也就是说,不是通常不允许您重命名打开的文件的 Windows),那绝对没有问题:一个打开的文件描述符仅仅算作一个硬链接(hard link)到文件的数据。

重命名文件的数据不会以某种方式与打开的文件描述符分离——将后者视为对该数据的一种“匿名”引用。

引用the close(2) manual :

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.

关于go - 在 golang 中,移动打开的文件会导致泄漏或任何其他问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52821247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com