【发布时间】:2021-02-17 05:27:30
【问题描述】:
我是 Lua 新手,对 Lua 中的内存管理有疑问。
问题1)在使用io.popen()调用函数时,我看到很多Lua程序员在使用popen()函数后写了一个close语句。我想知道这是什么原因?比如演示看这段代码:
handle = io.popen("ls -a")
output = handle:read("*all")
handle:close()
print(output)
handle = io.popen("date")
output = handle:read("*all")
handle:close()
print(output)
我听说 Lua 可以自己管理内存。那么我真的需要像上面那样写handle:close吗?如果我只是忽略handle:close() 语句并像这样写它,内存会发生什么?
handle = io.popen("ls -a")
handle = io.popen("date")
output = handle:read("*all")
问题2)从question 1中的代码来看,在内存使用方面,我们可以将handle:close()语句写在最后一行而不是这样吗?:
handle = io.popen("ls -a")
output = handle:read("*all")
-- handle:close() -- dont close it yet do at the end
print(output)
handle = io.popen("date") -- this use the same variable `handle` previously
output = handle:read("*all")
handle:close() -- only one statement to close all above
print(output)
您可以看到,当我使用io.popen 时,我没有从第一个语句中关闭它,但我在最后关闭它,这是否会使程序变慢,因为我最后只使用一个 close 语句关闭它?
【问题讨论】:
-
file:close()与内存管理无关。您应该尽快关闭打开的文件句柄,因为它是非常有限的操作系统资源。您不能同时打开很多文件。 -
你的意思是
io.popen是一个文件处理方法吗?我的意思是io.popen不是io.open -
io.popen创建一个管道并为您提供该管道的句柄。这是一个类似文件的句柄。 -
Lua 确实会在最近的 GC 周期中自动关闭文件处理程序,但它被不可预测地推迟了。它可能会在值未使用数小时后发生。
-
您仍然需要关闭句柄。在第二个示例中,您只是用新句柄重新分配变量,使旧句柄无法访问。 GC 可能会明智地清除参考内存,但操作系统在进程完成之前无法知道这一点......
标签: lua