我该如何在Lua中tail -F一个日志文件(带截断处理)?

我想在 Lua 中获取 tailftail -F 等类似工具的输出,而不会有阻塞或锁定的情况。如果文件被截断或日志轮换,程序将检测到并返回到开头。这似乎是一个级别 1 的问题,但对我来说看起来很奇怪。我只是无法想出解决方案。有人能分享一些代码吗?

点赞
用户234175
用户234175

有两个思路,你可以直接将 tail -F 的输出管道直接传入脚本执行中。然后你就可以从 stdin 中读取它。可能是这样的:

local c = 0
for line in io.stdin:lines() do
  c = c + 1
  print(c, line)
end

这种方法的问题是 tail 使用 stderr 报告文件截断,所以除非你找到某种方法将 stderr 重定向到 stdin,否则脚本将无法看到它。

另一个思路是在主循环之前使用 io.popen 强制进行 stderr -> stdin 重定向。然后你可以使用任何标准的模式匹配器来检查 tail 截断。

local tailin = io.popen('tail -F '..(...)..' 2>&1', 'r')

local c = 0
for line in tailin:lines() do
  c = c + 1
  print(c, line)
  c = line:match 'truncated' and 0 or c
end

注意,这两种方法都是阻塞的。

2013-06-29 06:49:45