简体   繁体   English

tail -f 在内部如何工作

[英]How does tail -f works internally

If I run this command:如果我运行这个命令:

tail -f file.txt

I will see changes in real time.我会实时看到变化。

My question is: How does it work?我的问题是:它是如何工作的? Is there a way for a process to be notified each time a file is changed?有没有办法在每次文件更改时通知进程?

Or is it a loop, like watch command do?或者它是一个循环,就像 watch 命令一样?

Thanks谢谢

With --follow (-f), tail defaults to following the file descriptor, which means that even if a tail'ed file is renamed, tail will continue to track its end.使用 --follow (-f) 时,tail 默认跟随文件描述符,这意味着即使 tail 的文件被重命名,tail 也会继续跟踪它的末尾。 This default behavior is not desirable when you re‐ ally want to track the actual name of the file, not the file descriptor (eg, log rotation).当你真的想跟踪文件的实际名称而不是文件描述符(例如,日志轮换)时,这种默认行为是不可取的。 Use --follow=name in that case.在这种情况下使用 --follow=name 。 That causes tail to track the named file in a way that accommodates renaming, re‐ moval and creation.这导致 tail 以适应重命名、删除和创建的方式跟踪命名文件。

The tail -f command works by continuously polling the file for changes and printing any new data that is added to the end of the file. tail -f 命令的工作原理是不断轮询文件的更改并打印添加到文件末尾的任何新数据。 When you run tail -f file.txt, the tail command opens the file and reads the last few lines (the default is 10 lines).当您运行 tail -f file.txt 时,tail 命令会打开文件并读取最后几行(默认为 10 行)。 It then waits for new data to be added to the file, and when it detects that the file has been modified, it reads the new data and prints it to the terminal.然后它等待新数据添加到文件中,当它检测到文件已被修改时,它会读取新数据并将其打印到终端。 This process continues indefinitely until you terminate the tail command.此过程无限期地继续,直到您终止 tail 命令。

One way to implement this behavior would be to use a loop that periodically checks the file for changes and prints any new data.实现此行为的一种方法是使用循环来定期检查文件的更改并打印任何新数据。 The watch command works in a similar way, although it runs a specified command at regular intervals and displays the output in the terminal. watch命令以类似的方式工作,尽管它定期运行指定的命令并在终端中显示 output。

There are other ways to monitor a file for changes.还有其他方法可以监视文件的更改。 For example, some operating systems provide APIs that allow processes to be notified when a file is modified .例如,一些操作系统提供的 API 允许在文件被修改时通知进程 This can be more efficient than continuously polling the file, as it allows the process to be notified of changes as they occur rather than having to constantly check for them.这比连续轮询文件更有效,因为它允许进程在发生更改时得到通知,而不必不断地检查它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM