是否检测到该日志文件已在POSIX系统上被删除或截断? [英] Detecting that log file has been deleted or truncated on POSIX systems?

查看:96
本文介绍了是否检测到该日志文件已在POSIX系统上被删除或截断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个长时间运行的进程将日志文件写入.假设日志文件无限期保持打开状态.假设粗心的系统管理员删除了该日志文件.程序可以检测到这种情况吗?

Suppose a long-running process writes to a log file. Suppose that log file is kept open indefinitely. Suppose that a careless system administrator deletes that log file. Can the program detect that this has happened?

可以安全地假设fstat()将报告已删除文件的链接计数为零吗?

Is it safe to assume that fstat() will report a link count of zero for a deleted file?

在我看来,截断有些棘手.部分取决于文件描述符是否以O_APPEND模式运行.如果日志文件未使用O_APPEND运行,则程序的日志描述符的当前写入位置不会更改,并且截断会删除前导字节,但程序会继续在末尾"进行写入,从而留出间隔幻影零字节(它们读为零,但不一定占用磁盘空间).

Truncation, it seems to me, is slightly trickier. In part, it depends on whether the file descriptor is running in O_APPEND mode. If the log file is not running with O_APPEND, then the current write position of the program's log descriptor doesn't change, and the truncation removes the leading bytes, but the program continues to write at 'the end', leaving a gap of phantasmal zero bytes (they read as zeroes, but don't necessarily occupy space on disk).

如果程序使用O_APPEND运行,则它将在当前存在的文件末尾写入.观察截断的唯一方法是注意文件位置不在程序期望的位置,这又意味着要明确跟踪该位置.

If the program runs with O_APPEND, then it will write at the end of the file as it currently exists. The only way to observe the truncation is to note that the file position is not where the program expected it - which in turn means tracking that position explicitly.

总的来说,我并不担心删节是删除,但任何想法都将受到欢迎.

On the whole, I'm not so worried about truncation as deletion, but any thoughts would be welcome.

推荐答案

如果文件是硬链接或重命名的,则检查fstat()返回的链接计数为零将失败.相反,我可能会定期将stat()的inode数与fstat()的inode数进行比较.

Checking that fstat() returns a link count of zero would fail if the file was hard linked or renamed. I would probably instead periodically compare stat()'s inode number against fstat()'s.

我不确定截断.

tail -F检查删除和可能的截断,因此我将检查其来源以了解其实现方式.

tail -F checks for deletion and maybe truncation, so I'd check its source to see how it implements it.

这篇关于是否检测到该日志文件已在POSIX系统上被删除或截断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆