简体   繁体   中英

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?

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. 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. That causes tail to track the named file in a way that accommodates renaming, re‐ moval and creation.

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. When you run tail -f file.txt, the tail command opens the file and reads the last few lines (the default is 10 lines). 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.

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.

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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