Taskadvanced
Follow a growing file
Also called tail -f, tail -F, follow a log file, watch a log file for new lines, follow a file after log rotation.
Read each new line of a file as it grows, as tail -F does, and keep the lines when the file is truncated, renamed, deleted or made again under the same name.
- Evidence
- Code in 9 languages
Task
Follow a file that grows, and get each line that a program adds to it, as tail -f and tail -F do. For tail -f, POSIX says: "do not terminate after the last line of the input file has been copied, but read and copy further bytes from the input file when they become available."1 A log file also changes in other ways. A program can truncate it, or rename it and make a new file with the same name. GNU tail -F follows the name: "That is, tail will attempt to reopen a file when it is removed."2 This page follows the name, as tail -F does.
The follower is an object with a poll operation. Each poll returns the complete lines that the file got since the last poll. A loop that polls at an interval and stops on a condition is a small part on top of it. The entry of the tests is follow_file(path, initial, steps). It writes initial to the file, makes a follower, does each step and returns the lines of each poll. A step can append text to the file or to path.1, truncate the file, rotate it (rename it to path.1 and make a new empty file at path), delete it, make it again, or poll.
This page uses these rules:
- The follower starts at the end of the file. The text that is in the file at the start gives no lines, also when it ends in a part of a line.
- A line ends at LF, and the LF is not in the line. A CR stays at the end of the line. The bytes after the last LF wait for the next poll, because the program can still be writing that line.
- A line is UTF-8 text. The follower splits the bytes at each LF first, and decodes each line after.
- A truncation starts the file again. If the open file is now shorter than the read offset, the bytes that wait become a line, and the follower reads the file again from byte 0.
- A rename or a delete ends the old file. The follower reads the rest of the old file. Then the bytes that wait become a line, and the follower closes the old file. If a file is at the path, the follower opens it and reads it from byte 0.
If no file is at the path when the follower starts, the follower reports an error.
Solutions
The follower keeps the file open, and keeps a read offset and the bytes after the last LF. Each poll does these steps:
- Get the identity of the file at the path, if a file is there. A file is "uniquely identified by the combination of the st_ino and st_dev fields."3 Do this step first. Then the read in step 3 gets each byte that the old file got before a rename.
- Get the size of the open file.
fstat"shall obtain information about an open file associated with the file descriptor fildes".4 If the size is less than the offset, the file was truncated. Then the bytes that wait become a line, and the offset goes back to 0. - Read from the offset to the end of the open file. Split the bytes at each LF, and decode each complete line. Keep the bytes after the last LF.
- If no file is at the path, or the file there is not the open file, the bytes that wait become a line. Close the open file.
- If no file is open and a file is at the path, open it and read it from byte 0, as in step 3.
JavaScript, TypeScript, Java, Go, C and C++ read at the offset, with pread or a function like it. pread reads "from a given position in the file without changing the file offset."5 The poll does not wait, and does not loop. Each solution except JavaScript and TypeScript has also a follow function that polls at an interval until a stop condition is true. The tests call it only with lines that are in the file before it starts, and stop it after 2 lines or after a fixed number of polls.
There is no C# solution. .NET gives the attributes, times, name and Unix mode of a file through FileSystemInfo, but no device number and no inode number.6 So a C# solution cannot tell the file at the path from the open file after a rotation.
- Python. The file is open in binary mode.
os.statgets the path andos.fstatgets the open file, andos.path.samestatcompares them: it returns "True if the stat tuples stat1 and stat2 refer to the same file."7bytes.split(b'\n')splits the bytes, and the last part waits.decode()raisesUnicodeDecodeErrorfor bytes that are not UTF-8.follow(path, interval, stop)makes the follower at once and returns a generator. A missing file raisesFileNotFoundError. - JavaScript and TypeScript (Node.js).
fs.statSync(path, { bigint: true, throwIfNoEntry: false })gets the path. The optionthrowIfNoEntryis "Whether an exception will be thrown if no file system entry exists, rather than returning undefined".8fstatSyncgets the open file, and the code comparesdevandinoasbigintvalues.readSyncreads at the offset: "If position is a non-negative integer, the current file position will remain unchanged."8buf.toString('utf8', start, end)decodes each line. A missing file throws an error with the codeENOENT. The TypeScript file adds types only. - Java. A
FileChannelreads at the offset, withread(buf, position), which "Reads a sequence of bytes from this channel into the given buffer, starting at the given file position."9 Itssize()"Returns the current size of this channel's file."9 Java cannot get the attributes of an open channel. So the solution takesBasicFileAttributes.fileKey()of the path just after the open, and compares it with the key of the path at each poll.fileKey()"Returns an object that uniquely identifies the given file, or null if a file key is not available."10 A missing file throwsNoSuchFileException. - Go.
os.Statgets the path andFile.Statgets the open file.os.SameFilecompares them: "on Unix this means that the device and inode fields of the two underlying structures are identical".11File.ReadAtreads at the offset.string(b)keeps the bytes as they are, also bytes that are not UTF-8.Follow(interval, stop, emit)is a method of the follower, so the follower starts before the loop. A missing file gives an error that wrapsfs.ErrNotExist. - Rust.
fs::metadatagets the path andFile::metadatagets the open file.MetadataExtgivesdev, which "Returns the ID of the device containing the file.", andino, which "Returns the inode number."12seekgoes to the offset,read_to_endreads the new bytes, andString::from_utf8_lossydecodes each line. A missing file gives an error of kindNotFound. - C.
follower_openopens the file, andfollower_pollcalls a callback with each line and its length.statgets the path,fstatgets the open file, and the code comparesst_devandst_ino.preadreads at the offset into a buffer that grows. The bytes stay as they are. A function returns -1 witherrnoset on an error, so a missing file givesENOENT. - C++. The class
Followeruses the same POSIX calls as the C solution, and closes the file in its destructor.pollreturns astd::vector<std::string>. An error throwsstd::system_errorwith the value oferrno. - Bash. The follower keeps the file open on file descriptor 9, and keeps its state in global variables.
read -r -u 9reads each line. The Bash manual says thatreadwill "Read one line from the standard input, or from the file descriptor fd supplied as an argument to the -u option".13 At the end of the file,readfails but puts the bytes after the last LF in the variable, so they wait. Bash cannot get the attributes of an open file, so the code takes the inode number of the path fromls -dijust after the open. For-i,lswill "write the file's file serial number".14wc -con the path gives the size. Bash cannot seek, so after a truncation the code opens the file again. A NUL byte in the file is lost.follow_pollmust run in the shell itself, not in$(...)or in a pipeline, because a subshell does not change the state of the follower. A missing file makesfollow_openprint a message and return 1.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
append-lines: the file starts withold, and getsa,b, thenc. The polls givea,band thenc. The lineolddoes not come.no-change: two polls with no new bytes give no lines.partial-line:abwaits, thencLFdgivesabc, then LF givesd.start-mid-line: the file starts withabcand no LF. The new bytesdLFeLF givedande, because the follower starts at the end of the file.empty-lineandcrlf: LF LFaLF gives two empty lines anda.aCRLFbCRLF givesaCR andbCR.non-ascii:caféandnaïvecome back as they are.truncate,truncate-and-writeandtruncate-partial: after a truncation, the follower reads the new text from byte 0. Intruncate-and-write, the new textbLF is shorter than the old textaaaaLF, so the size shows the truncation. Intruncate-partial, the bytesabcthat waited come first, as a line.rotateandrotate-twice: after each rotation, the follower reads the new file from byte 0.rotate-late-writes: after the rotation, the old file gets2and the new file gets3. The poll gives2and then3, because the follower reads the rest of the old file before it opens the new file.rotate-partial:awaits, then the rotation makes it a line, andbcomes from the new file.delete,delete-partial,delete-and-createanddelete-and-create-between-polls: after a delete, the polls give no lines until a new file is at the path. The bytes that waited become a line. If the new file comes before the next poll, that poll gives its lines.
The cases in cases/errors.jsonl must give the error not-found. The toolchain does not load that file yet, so each test file holds that case by name. Each test file also appends 100000 lines with the numbers 0 to 99999, and checks that one poll gives all of them. Each test file except Python appends the first byte of é, polls, then appends the second byte and an LF, and checks that the next poll gives café. Each test file except JavaScript and TypeScript, which have no follow function, writes 2 lines after the follower starts and stops the follow loop after 2 lines or after a fixed number of polls.
Pitfalls
tail -fdoes not follow a rotation. GNUtail -ffollows the descriptor, and "When following a descriptor, tail does not detect that the file has been unlinked or renamed and issues no message".2 After a log rotation, it waits for bytes in the old file, and the new file gets the lines. Usetail -F, which is "the same as --follow=name --retry".2 When a follower opens the file again, it must compare the device and the inode number, not only the name. A rename keeps the old file. POSIX says that the new name shall "refer either to the file referred to by new or old before the operation began".15 The inode number shows the difference:
dir=$(mktemp -d)
cd "$dir"
inode() { ls -di "$1" | awk '{ print $1 }'; }
printf 'a\n' > app.log
before=$(inode app.log)
: > app.log # truncate
if [ "$(inode app.log)" = "$before" ]; then echo 'truncate: same file'; else echo 'truncate: new file'; fi
before=$(inode app.log)
mv app.log app.log.1 && : > app.log # rotate
if [ "$(inode app.log)" = "$before" ]; then echo 'rotate: same file'; else echo 'rotate: new file'; fi
if [ "$(inode app.log.1)" = "$before" ]; then echo 'app.log.1 is the old file'; fi
cd / && rm -rf "${dir:?}"
truncate: same file
rotate: new file
app.log.1 is the old file
- A truncation is not always visible in the size. The follower sees a truncation only when the size is less than its offset. A truncation keeps the file: with
O_TRUNC, "its length shall be truncated to 0, and the mode and owner shall be unchanged."16 GNUtailhas the same limit. When the file has shrunk, it "resumes tracking from the start of the file, assuming it has been truncated to 0".2 If the program then writes more bytes than the offset before the next poll, the size is not less, and the follower reads from the old offset, in the middle of the new text. Then the follower loses lines:
import os
import tempfile
with tempfile.TemporaryDirectory() as directory:
path = os.path.join(directory, 'app.log')
with open(path, 'w') as f:
f.write('old 1\nold 2\n')
offset = os.path.getsize(path) # the follower has read up to here
with open(path, 'w') as f: # O_TRUNC: the same file, now empty
f.write('new line 1\nnew line 2\n')
size = os.path.getsize(path)
print('offset:', offset, 'size:', size)
print('truncation seen:', size < offset)
with open(path, 'rb') as f:
f.seek(offset)
print('read from the offset:', f.read())
offset: 12 size: 22
truncation seen: False
read from the offset: b'ew line 2\n'
- Decode each line, not each read. A read can stop in the middle of a character. If the code decodes each read, the two parts of
ébecome two replacement characters. Split the bytes at each LF first, as all the solutions here do. In Node.js, aStringDecoderalso works. Its documentation says that "an internal buffer is used to ensure that the decoded string does not contain any incomplete multibyte characters."17 The JavaScript block shows the problem:
const show = (s) => s.replace(/[^\x20-\x7e]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
const bytes = Buffer.from("café\n");
const first = bytes.subarray(0, 4); // c, a, f and the first byte of é
const second = bytes.subarray(4);
console.log("decode each read:", show(first.toString("utf8") + second.toString("utf8")));
console.log("decode the line: ", show(Buffer.concat([first, second]).toString("utf8")));
decode each read: caf\ufffd\ufffd\u000a
decode the line: caf\u00e9\u000a
- The last line can be a part of a line. When the read gets to the end of the file, the program can be in the middle of a line. Keep those bytes for the next poll. Return them as a line only when the file is truncated, renamed or deleted, because no more bytes come for them then.
- Look at the path before the read. If the poll reads first and looks at the path after, a program can append to the file and rename it between the two steps. Then the poll sees the new file, closes the old file and loses the bytes that it did not read.
- Keep the old file open. POSIX
unlinksays that if a process has the file open, "the removal of the file contents shall be postponed until there are no such references to the file."18 So the follower can read the rest of a file after a rename or a delete. POSIX makes the device and the inode number unique for the files that are visible in the file tree.3 If the follower closes the file after each poll and keeps only the inode number, the old file can go, a new file can get the same number, and the follower takes the new file for the old file. - Java takes the file key from the path. The key comes from the path just after the open, so a rename between the open and that step gives the key of the wrong file. On a system with no file key,
fileKey()returns null, and the Java solution takes the file as deleted at each poll, so it reads the file again and gives the lines again. On Linux and macOS, the key holds the device and the inode number. - A Python generator starts late. The body of a generator runs only at the first
next. If the generator opens the file, it starts at the end of the file at that time, and it loses the lines that came between the call and the firstnext. The Pythonfollowopens the file before it makes the generator. - Polling is not an event. A poll at an interval adds a delay and costs a system call when the file does not change. On Linux,
inotifygives events. But inotify "does not catch remote events that occur on network filesystems. (Applications must fall back to polling the filesystem to catch such events.)"19 Also "Inotify monitoring is inode-based", so a watch on the file stays on the old file after a rotation.19 A program that uses events must watch the directory, and must still read and compare as this page does.
Related tasks
- Watch a file for changes: get an event when a file changes, with inotify and the other system APIs.
- Read a file line by line: read the lines of a file that does not change.
- Print the first and last lines of a file:
headandtailwith no-f. - Rename a file: rename a file, which keeps the old file under the new name.
- Delete a file: delete a file, and what happens to a process that has it open.
- Line ending: LF, CRLF and CR, and why a CR stays in the line.
- UTF-8: the encoding of the lines, and how a character can take more than one byte.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/tail-a-growing-file/.
import os
import time
from collections.abc import Callable, Iterator
class Follower:
"""Follows a file that grows, as tail -F does, one poll at a time.
The follower keeps the file open, so it can read the rest of the file
after a rename or a delete. It starts at the end of the file. Raises
FileNotFoundError if no file is at path.
"""
def __init__(self, path: str | os.PathLike[str]) -> None:
self.path = path
self.file = open(path, "rb")
self.file.seek(0, os.SEEK_END)
self.pending = b"" # the bytes after the last LF
def poll(self) -> list[str]:
"""Returns the complete lines that were added since the last poll."""
lines: list[str] = []
if self.file is not None:
# Look at the path before the read. Then the read gets each byte
# that was written before a rename or a delete.
try:
now = os.stat(self.path)
except FileNotFoundError:
now = None
open_ = os.fstat(self.file.fileno())
if open_.st_size < self.file.tell():
# The file is shorter than the offset, so it was truncated.
self._flush(lines)
self.file.seek(0)
self._read(lines)
if now is None or not os.path.samestat(now, open_):
# The file was deleted or renamed. Its rest is read.
self._flush(lines)
self.file.close()
self.file = None
if self.file is None:
try:
self.file = open(self.path, "rb")
except FileNotFoundError:
return lines
self._read(lines)
return lines
def close(self) -> None:
if self.file is not None:
self.file.close()
self.file = None
def _read(self, lines: list[str]) -> None:
assert self.file is not None
parts = (self.pending + self.file.read()).split(b"\n")
self.pending = parts.pop()
lines.extend(part.decode() for part in parts)
def _flush(self, lines: list[str]) -> None:
if self.pending:
lines.append(self.pending.decode())
self.pending = b""
def follow(path: str, interval: float = 0.5, stop: Callable[[], bool] = lambda: False) -> Iterator[str]:
"""Returns an iterator over each new line of the file at path.
The follower starts now, at the end of the file. The iterator polls the
file each interval seconds, and ends when stop returns True.
"""
follower = Follower(path) # not in the generator, which starts later
return _lines(follower, interval, stop)
def _lines(follower: Follower, interval: float, stop: Callable[[], bool]) -> Iterator[str]:
try:
while not stop():
yield from follower.poll()
time.sleep(interval)
finally:
follower.close()
def follow_file(path: str, initial: str, steps: list[str]) -> list[list[str]]:
"""Writes initial to path, makes a follower and does the steps."""
with open(path, "wb") as f:
f.write(initial.encode())
follower = Follower(path)
old = path + ".1"
polls = []
try:
for step in steps:
op, _, text = step.partition(":")
if op == "poll":
polls.append(follower.poll())
elif op in ("append", "append-old"):
with open(path if op == "append" else old, "ab") as f:
f.write(text.encode())
elif op == "truncate":
with open(path, "wb") as f:
f.write(text.encode())
elif op == "rotate":
os.replace(path, old)
open(path, "xb").close()
elif op == "delete":
os.remove(path)
elif op == "create":
with open(path, "xb") as f:
f.write(text.encode())
else:
raise ValueError(f"bad step: {step!r}")
finally:
follower.close()
return polls
test_follow_file.py 62 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/tail-a-growing-file/.
import json
import os
import tempfile
import time
import unittest
from pathlib import Path
from follow_file import Follower, follow, follow_file
CASES = Path(__file__).resolve().parents[2] / "cases"
def load(name: str) -> list[dict]:
with open(CASES / name, encoding="utf-8") as f:
return [json.loads(line) for line in f]
class FollowFileTest(unittest.TestCase):
def setUp(self) -> None:
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.dir = tmp.name
def test_cases(self) -> None:
for case in load("basic.jsonl") + load("edge.jsonl"):
with self.subTest(case["name"]), tempfile.TemporaryDirectory() as d:
args = case["args"]
got = follow_file(os.path.join(d, args["path"]), args["initial"], args["steps"])
self.assertEqual(got, case["expect"])
def test_not_found(self) -> None:
with self.assertRaises(FileNotFoundError):
follow_file(os.path.join(self.dir, "missing", "followed.txt"), "", ["poll"])
def test_many_lines(self) -> None:
path = os.path.join(self.dir, "followed.txt")
Path(path).write_bytes(b"")
follower = Follower(path)
with open(path, "ab") as f:
f.write("".join(f"{i}\n" for i in range(100000)).encode())
lines = follower.poll()
follower.close()
self.assertEqual(len(lines), 100000)
self.assertEqual(lines[0], "0")
self.assertEqual(lines[-1], "99999")
def test_follow(self) -> None:
path = os.path.join(self.dir, "followed.txt")
Path(path).write_bytes(b"old\n")
deadline = time.monotonic() + 5
lines = follow(path, interval=0.01, stop=lambda: time.monotonic() > deadline)
with open(path, "ab") as f:
f.write(b"a\nb\n")
self.assertEqual([next(lines), next(lines)], ["a", "b"])
lines.close()
if __name__ == "__main__":
unittest.main()
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
#include "follow_file.hpp"
#include <cerrno>
#include <stdexcept>
#include <string_view>
#include <system_error>
#include <thread>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
namespace fs = std::filesystem;
namespace {
[[noreturn]] void fail(const std::string& what) {
throw std::system_error(errno, std::generic_category(), what);
}
} // namespace
Follower::Follower(fs::path path) : path_(std::move(path)) {
fd_ = ::open(path_.c_str(), O_RDONLY);
struct stat st;
if (fd_ < 0 || ::fstat(fd_, &st) != 0) {
int e = errno;
close();
errno = e;
fail(path_.string());
}
offset_ = st.st_size;
}
Follower::~Follower() { close(); }
void Follower::close() {
if (fd_ >= 0) {
::close(fd_);
fd_ = -1;
}
}
std::vector<std::string> Follower::poll() {
std::vector<std::string> lines;
if (fd_ >= 0) {
// Look at the path before the read. Then the read gets each byte that
// was written before a rename or a delete.
struct stat now, open_file;
bool found = ::stat(path_.c_str(), &now) == 0;
if (!found && errno != ENOENT) {
fail(path_.string());
}
if (::fstat(fd_, &open_file) != 0) {
fail(path_.string());
}
if (open_file.st_size < offset_) {
// The file is shorter than the offset, so it was truncated.
flush(lines);
offset_ = 0;
}
read(lines);
if (!found || now.st_dev != open_file.st_dev || now.st_ino != open_file.st_ino) {
// The file was deleted or renamed. Its rest is read.
flush(lines);
close();
}
}
if (fd_ < 0) {
fd_ = ::open(path_.c_str(), O_RDONLY);
if (fd_ < 0) {
if (errno == ENOENT) {
return lines;
}
fail(path_.string());
}
offset_ = 0;
read(lines);
}
return lines;
}
void Follower::follow(std::chrono::milliseconds interval, const std::function<bool()>& stop,
const std::function<void(std::string)>& emit) {
for (;;) {
for (auto& line : poll()) {
emit(std::move(line));
}
if (stop()) {
return;
}
std::this_thread::sleep_for(interval);
}
}
void Follower::read(std::vector<std::string>& lines) {
char buf[65536];
for (;;) {
ssize_t n = ::pread(fd_, buf, sizeof buf, offset_);
if (n < 0 && errno == EINTR) {
continue;
}
if (n < 0) {
fail(path_.string());
}
if (n == 0) {
return;
}
offset_ += n;
// Split the bytes at each LF. pending_ has no LF.
std::string_view data(buf, static_cast<std::size_t>(n));
for (auto lf = data.find('\n'); lf != std::string_view::npos; lf = data.find('\n')) {
pending_.append(data.substr(0, lf));
lines.push_back(std::move(pending_));
pending_.clear();
data.remove_prefix(lf + 1);
}
pending_.append(data);
}
}
void Follower::flush(std::vector<std::string>& lines) {
if (!pending_.empty()) {
lines.push_back(std::move(pending_));
pending_.clear();
}
}
namespace {
// Writes text to the file at path, which open opens with flags.
void write_text(const fs::path& path, int flags, std::string_view text) {
int fd = ::open(path.c_str(), O_WRONLY | flags, 0644);
if (fd < 0) {
fail(path.string());
}
while (!text.empty()) {
ssize_t n = ::write(fd, text.data(), text.size());
if (n < 0 && errno == EINTR) {
continue;
}
if (n < 0) {
int e = errno;
::close(fd);
errno = e;
fail(path.string());
}
text.remove_prefix(static_cast<std::size_t>(n));
}
if (::close(fd) != 0) {
fail(path.string());
}
}
} // namespace
std::vector<std::vector<std::string>> follow_file(const fs::path& path, const std::string& initial,
const std::vector<std::string>& steps) {
write_text(path, O_CREAT | O_TRUNC, initial);
Follower follower(path);
fs::path old = path;
old += ".1";
std::vector<std::vector<std::string>> polls;
for (const auto& step : steps) {
auto colon = step.find(':');
std::string op = step.substr(0, colon);
std::string text = colon == std::string::npos ? "" : step.substr(colon + 1);
if (op == "poll") {
polls.push_back(follower.poll());
} else if (op == "append") {
write_text(path, O_CREAT | O_APPEND, text);
} else if (op == "append-old") {
write_text(old, O_CREAT | O_APPEND, text);
} else if (op == "truncate") {
write_text(path, O_CREAT | O_TRUNC, text);
} else if (op == "rotate") {
fs::rename(path, old);
write_text(path, O_CREAT | O_EXCL, "");
} else if (op == "delete") {
fs::remove(path);
} else if (op == "create") {
write_text(path, O_CREAT | O_EXCL, text);
} else {
throw std::invalid_argument("bad step: " + step);
}
}
return polls;
}
follow_file.hpp 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
#pragma once
#include <chrono>
#include <filesystem>
#include <functional>
#include <string>
#include <vector>
#include <sys/types.h>
// Reads the lines that are added to a file, one poll at a time, as tail -F
// does. The follower keeps the file open, so it can read the rest of the file
// after a rename or a delete. std::filesystem cannot get the identity of an
// open file, so the follower uses the POSIX calls open, fstat and pread. Each
// error is a std::system_error.
class Follower {
public:
// Opens the file at path and starts at its end. The error code is
// std::errc::no_such_file_or_directory if no file is at path.
explicit Follower(std::filesystem::path path);
Follower(const Follower&) = delete;
Follower& operator=(const Follower&) = delete;
~Follower();
// Returns the complete lines that were added since the last poll.
std::vector<std::string> poll();
// Calls emit with each new line. Polls the file each interval, and
// returns when stop returns true.
void follow(std::chrono::milliseconds interval, const std::function<bool()>& stop,
const std::function<void(std::string)>& emit);
private:
void read(std::vector<std::string>& lines);
void flush(std::vector<std::string>& lines);
void close();
std::filesystem::path path_;
int fd_ = -1; // -1 if no file is open
off_t offset_ = 0;
std::string pending_; // the bytes after the last LF
};
// Writes initial to path, makes a follower, does the steps and returns the
// lines of each poll.
std::vector<std::vector<std::string>> follow_file(const std::filesystem::path& path, const std::string& initial,
const std::vector<std::string>& steps);
test_follow_file.cpp 125 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
#include "follow_file.hpp"
#include <fstream>
#include <iostream>
#include <string>
#include <system_error>
#include <unistd.h>
#include <vector>
namespace fs = std::filesystem;
namespace {
int failures = 0;
void check(bool ok, const std::string& name, const char* what) {
if (!ok) {
std::cerr << "FAIL " << name << ": " << what << '\n';
failures++;
}
}
// Each poll is one string, with an LF after each line.
struct Case {
std::string name, initial;
std::vector<std::string> steps;
std::vector<std::string> want;
};
const std::vector<Case> cases = {
{"append-lines", "old\n", {"append:a\nb\n", "poll", "append:c\n", "poll"}, {"a\nb\n", "c\n"}},
{"partial-line", "", {"append:ab", "poll", "append:c\nd", "poll", "append:\n", "poll"}, {"", "abc\n", "d\n"}},
{"rotate", "1\n", {"append:2\n", "poll", "rotate", "append:3\n", "poll"}, {"2\n", "3\n"}},
{"truncate", "", {"append:a\nb\n", "poll", "truncate:", "poll", "append:c\n", "poll"}, {"a\nb\n", "", "c\n"}},
{"no-change", "x\n", {"poll", "poll"}, {"", ""}},
{"empty-line", "", {"append:\n\na\n", "poll"}, {"\n\na\n"}},
{"crlf", "", {"append:a\r\nb\r\n", "poll"}, {"a\r\nb\r\n"}},
{"truncate-and-write", "", {"append:aaaa\n", "poll", "truncate:b\n", "poll"}, {"aaaa\n", "b\n"}},
{"truncate-partial", "", {"append:abc", "poll", "truncate:d\n", "poll"}, {"", "abc\nd\n"}},
{"rotate-late-writes", "", {"append:1\n", "poll", "rotate", "append-old:2\n", "append:3\n", "poll"}, {"1\n", "2\n3\n"}},
{"rotate-partial", "", {"append:a", "poll", "rotate", "append:b\n", "poll"}, {"", "a\nb\n"}},
{"rotate-twice", "", {"append:1\n", "poll", "rotate", "append:2\n", "poll", "rotate", "append:3\n", "poll"}, {"1\n", "2\n", "3\n"}},
{"delete", "", {"append:1\n", "poll", "delete", "poll", "poll"}, {"1\n", "", ""}},
{"delete-partial", "", {"append:x", "poll", "delete", "poll"}, {"", "x\n"}},
{"delete-and-create", "", {"append:1\n", "poll", "delete", "poll", "create:2\n", "poll"}, {"1\n", "", "2\n"}},
{"delete-and-create-between-polls", "", {"append:1\n", "poll", "delete", "create:2\n", "poll"}, {"1\n", "2\n"}},
{"start-mid-line", "abc", {"append:d\ne\n", "poll"}, {"d\ne\n"}},
{"non-ascii", "", {"append:caf\303\251\nna\303\257ve\n", "poll"}, {"caf\303\251\nna\303\257ve\n"}},
};
std::vector<std::string> join(const std::vector<std::vector<std::string>>& polls) {
std::vector<std::string> joined;
for (const auto& lines : polls) {
std::string s;
for (const auto& line : lines) {
s += line + '\n';
}
joined.push_back(s);
}
return joined;
}
} // namespace
int main() {
fs::path dir = fs::temp_directory_path() / ("follow-file-" + std::to_string(getpid()));
fs::create_directory(dir);
fs::path path = dir / "followed.txt";
for (const auto& c : cases) {
check(join(follow_file(path, c.initial, c.steps)) == c.want, c.name, "polls");
fs::remove_all(dir);
fs::create_directory(dir);
}
// not-found
try {
follow_file(dir / "missing" / "followed.txt", "", {"poll"});
check(false, "not-found", "no error");
} catch (const std::system_error& e) {
check(e.code() == std::errc::no_such_file_or_directory, "not-found", "code");
}
try {
Follower follower(dir / "missing.txt");
check(false, "not-found", "no error");
} catch (const std::system_error& e) {
check(e.code() == std::errc::no_such_file_or_directory, "not-found", "code");
}
// 100000 lines in one poll.
std::string text = "append:";
for (int i = 0; i < 100000; i++) {
text += std::to_string(i) + '\n';
}
auto polls = follow_file(path, "", {text, "poll"});
check(polls.size() == 1 && polls[0].size() == 100000, "many-lines", "size");
check(polls[0].front() == "0" && polls[0].back() == "99999", "many-lines", "lines");
fs::remove(path);
// A character across two polls.
polls = follow_file(path, "", {"append:caf\xc3", "poll", "append:\xa9\n", "poll"});
check(join(polls) == std::vector<std::string>{"", "caf\xc3\xa9\n"}, "character-across-polls", "polls");
fs::remove(path);
// follow: the lines that come after the follower starts.
std::ofstream(path, std::ios::binary) << "old\n";
Follower follower(path);
std::ofstream(path, std::ios::binary | std::ios::app) << "a\nb\n";
std::vector<std::string> lines;
int n = 0;
follower.follow(
std::chrono::milliseconds(10), [&] { return lines.size() >= 2 || ++n > 500; },
[&](std::string line) { lines.push_back(std::move(line)); });
check(lines == std::vector<std::string>{"a", "b"}, "follow", "lines");
fs::remove_all(dir);
if (failures > 0) {
return 1;
}
std::cout << "all tests pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
public final class FollowFile {
private FollowFile() {}
/**
* Reads the lines that are added to a file, one poll at a time, as tail -F does. The follower
* keeps the file open, so it can read the rest of the file after a rename or a delete.
*/
public static final class Follower implements Closeable {
private final Path path;
private FileChannel channel; // null if no file is open
private Object key; // the identity of the open file
private long offset;
private ByteArrayOutputStream pending = new ByteArrayOutputStream(); // the bytes after the last LF
/** Opens the file at path and starts at its end. Throws NoSuchFileException if no file is at path. */
public Follower(Path path) throws IOException {
this.path = path;
open();
offset = channel.size();
}
private void open() throws IOException {
channel = FileChannel.open(path, StandardOpenOption.READ);
// Java cannot get the attributes of an open channel, so the key comes from the path just
// after the open. On Linux and macOS, the key holds the device and the inode number.
try {
key = Files.readAttributes(path, BasicFileAttributes.class).fileKey();
} catch (IOException e) {
close();
throw e;
}
}
/** Returns the complete lines that were added since the last poll. */
public List<String> poll() throws IOException {
List<String> lines = new ArrayList<>();
if (channel != null) {
// Look at the path before the read. Then the read gets each byte that was written before a
// rename or a delete.
Object now;
try {
now = Files.readAttributes(path, BasicFileAttributes.class).fileKey();
} catch (NoSuchFileException e) {
now = null;
}
if (channel.size() < offset) {
// The file is shorter than the offset, so it was truncated.
flush(lines);
offset = 0;
}
read(lines);
if (now == null || !Objects.equals(now, key)) {
// The file was deleted or renamed. Its rest is read.
flush(lines);
close();
}
}
if (channel == null) {
try {
open();
} catch (NoSuchFileException e) {
return lines;
}
offset = 0;
read(lines);
}
return lines;
}
/** Calls emit with each new line. Polls the file each interval, and returns when stop is true. */
public void follow(Duration interval, BooleanSupplier stop, Consumer<String> emit)
throws IOException, InterruptedException {
for (;;) {
poll().forEach(emit);
if (stop.getAsBoolean()) {
return;
}
Thread.sleep(interval);
}
}
@Override
public void close() throws IOException {
if (channel != null) {
FileChannel c = channel;
channel = null;
c.close();
}
}
private void read(List<String> lines) throws IOException {
ByteBuffer buf = ByteBuffer.allocate(65536);
for (int n; (n = channel.read(buf.clear(), offset)) > 0; ) {
offset += n;
// Split the bytes at each LF first, and decode each line after. A read can end in the
// middle of a UTF-8 character.
byte[] data = buf.array();
int start = 0;
for (int i = 0; i < n; i++) {
if (data[i] == '\n') {
pending.write(data, start, i - start);
lines.add(pending.toString(StandardCharsets.UTF_8));
pending.reset();
start = i + 1;
}
}
pending.write(data, start, n - start);
}
}
private void flush(List<String> lines) {
if (pending.size() > 0) {
lines.add(pending.toString(StandardCharsets.UTF_8));
pending.reset();
}
}
}
/** Writes initial to path, makes a follower, does the steps and returns the lines of each poll. */
public static List<List<String>> followFile(Path path, String initial, List<String> steps)
throws IOException {
Files.writeString(path, initial);
Path old = path.resolveSibling(path.getFileName() + ".1");
List<List<String>> polls = new ArrayList<>();
try (Follower follower = new Follower(path)) {
for (String step : steps) {
int colon = step.indexOf(':');
String op = colon < 0 ? step : step.substring(0, colon);
String text = colon < 0 ? "" : step.substring(colon + 1);
switch (op) {
case "poll" -> polls.add(follower.poll());
case "append" -> append(path, text);
case "append-old" -> append(old, text);
case "truncate" -> Files.writeString(path, text);
case "rotate" -> {
Files.move(path, old, StandardCopyOption.REPLACE_EXISTING);
Files.createFile(path);
}
case "delete" -> Files.delete(path);
case "create" -> Files.writeString(path, text, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
default -> throw new IllegalArgumentException("bad step: " + step);
}
}
}
return polls;
}
private static void append(Path path, String text) throws IOException {
Files.writeString(path, text, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
}
FollowFileTest.java 99 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class FollowFileTest {
@TempDir Path dir;
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("append-lines", "old\n", List.of("append:a\nb\n", "poll", "append:c\n", "poll"), List.of(List.of("a", "b"), List.of("c"))),
Arguments.of("partial-line", "", List.of("append:ab", "poll", "append:c\nd", "poll", "append:\n", "poll"), List.of(List.of(), List.of("abc"), List.of("d"))),
Arguments.of("rotate", "1\n", List.of("append:2\n", "poll", "rotate", "append:3\n", "poll"), List.of(List.of("2"), List.of("3"))),
Arguments.of("truncate", "", List.of("append:a\nb\n", "poll", "truncate:", "poll", "append:c\n", "poll"), List.of(List.of("a", "b"), List.of(), List.of("c"))),
Arguments.of("no-change", "x\n", List.of("poll", "poll"), List.of(List.of(), List.of())),
Arguments.of("empty-line", "", List.of("append:\n\na\n", "poll"), List.of(List.of("", "", "a"))),
Arguments.of("crlf", "", List.of("append:a\r\nb\r\n", "poll"), List.of(List.of("a\r", "b\r"))),
Arguments.of("truncate-and-write", "", List.of("append:aaaa\n", "poll", "truncate:b\n", "poll"), List.of(List.of("aaaa"), List.of("b"))),
Arguments.of("truncate-partial", "", List.of("append:abc", "poll", "truncate:d\n", "poll"), List.of(List.of(), List.of("abc", "d"))),
Arguments.of("rotate-late-writes", "", List.of("append:1\n", "poll", "rotate", "append-old:2\n", "append:3\n", "poll"), List.of(List.of("1"), List.of("2", "3"))),
Arguments.of("rotate-partial", "", List.of("append:a", "poll", "rotate", "append:b\n", "poll"), List.of(List.of(), List.of("a", "b"))),
Arguments.of("rotate-twice", "", List.of("append:1\n", "poll", "rotate", "append:2\n", "poll", "rotate", "append:3\n", "poll"), List.of(List.of("1"), List.of("2"), List.of("3"))),
Arguments.of("delete", "", List.of("append:1\n", "poll", "delete", "poll", "poll"), List.of(List.of("1"), List.of(), List.of())),
Arguments.of("delete-partial", "", List.of("append:x", "poll", "delete", "poll"), List.of(List.of(), List.of("x"))),
Arguments.of("delete-and-create", "", List.of("append:1\n", "poll", "delete", "poll", "create:2\n", "poll"), List.of(List.of("1"), List.of(), List.of("2"))),
Arguments.of("delete-and-create-between-polls", "", List.of("append:1\n", "poll", "delete", "create:2\n", "poll"), List.of(List.of("1"), List.of("2"))),
Arguments.of("start-mid-line", "abc", List.of("append:d\ne\n", "poll"), List.of(List.of("d", "e"))),
Arguments.of("non-ascii", "", List.of("append:caf\u00e9\nna\u00efve\n", "poll"), List.of(List.of("caf\u00e9", "na\u00efve"))));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void followFile(String name, String initial, List<String> steps, List<List<String>> want)
throws IOException {
assertEquals(want, FollowFile.followFile(dir.resolve("followed.txt"), initial, steps));
}
@Test
void notFound() {
assertThrows(NoSuchFileException.class,
() -> FollowFile.followFile(dir.resolve("missing/followed.txt"), "", List.of("poll")));
assertThrows(NoSuchFileException.class, () -> new FollowFile.Follower(dir.resolve("missing.txt")));
}
@Test
void manyLines() throws IOException {
StringBuilder text = new StringBuilder("append:");
for (int i = 0; i < 100000; i++) {
text.append(i).append('\n');
}
List<List<String>> polls =
FollowFile.followFile(dir.resolve("followed.txt"), "", List.of(text.toString(), "poll"));
assertEquals(100000, polls.get(0).size());
assertEquals("0", polls.get(0).get(0));
assertEquals("99999", polls.get(0).get(99999));
}
@Test
void characterAcrossPolls() throws IOException {
Path path = dir.resolve("followed.txt");
Files.writeString(path, "");
try (FollowFile.Follower follower = new FollowFile.Follower(path)) {
Files.write(path, new byte[] {'c', 'a', 'f', (byte) 0xc3}, StandardOpenOption.APPEND);
assertEquals(List.of(), follower.poll());
Files.write(path, new byte[] {(byte) 0xa9, '\n'}, StandardOpenOption.APPEND);
assertEquals(List.of("caf\u00e9"), follower.poll());
}
}
@Test
void follow() throws IOException, InterruptedException {
Path path = dir.resolve("followed.txt");
Files.writeString(path, "old\n");
List<String> lines = new ArrayList<>();
int[] polls = {0};
try (FollowFile.Follower follower = new FollowFile.Follower(path)) {
Files.writeString(path, "a\nb\n", StandardCharsets.UTF_8, StandardOpenOption.APPEND);
follower.follow(Duration.ofMillis(10), () -> lines.size() >= 2 || ++polls[0] > 500, lines::add);
}
assertEquals(List.of("a", "b"), lines);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
// open, fstat, pread and nanosleep are in POSIX, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "follow_file.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
int follower_open(struct follower *f, const char *path) {
*f = (struct follower){.fd = -1};
struct stat st;
f->path = malloc(strlen(path) + 1);
if (f->path == NULL) {
return -1;
}
strcpy(f->path, path);
f->fd = open(path, O_RDONLY);
if (f->fd < 0 || fstat(f->fd, &st) != 0) {
int e = errno;
follower_close(f);
errno = e;
return -1;
}
f->offset = st.st_size;
return 0;
}
void follower_close(struct follower *f) {
if (f->fd >= 0) {
close(f->fd);
}
free(f->path);
free(f->pending);
*f = (struct follower){.fd = -1};
}
static int flush(struct follower *f, follow_emit emit, void *arg) {
if (f->npending == 0) {
return 0;
}
size_t len = f->npending;
f->npending = 0;
return emit(f->pending, len, arg);
}
// Reads the new bytes, and calls emit with each complete line.
static int read_new(struct follower *f, follow_emit emit, void *arg) {
for (;;) {
if (f->cap - f->npending < 65536) {
size_t cap = f->npending + 65536;
char *bigger = realloc(f->pending, cap);
if (bigger == NULL) {
return -1;
}
f->pending = bigger;
f->cap = cap;
}
ssize_t n = pread(f->fd, f->pending + f->npending, f->cap - f->npending, f->offset);
if (n < 0 && errno == EINTR) {
continue;
}
if (n <= 0) {
return n < 0 ? -1 : 0;
}
f->offset += n;
// Split the bytes at each LF. The bytes before the new bytes have no LF.
size_t start = 0, end = f->npending + (size_t)n;
for (size_t i = f->npending; i < end; i++) {
if (f->pending[i] == '\n') {
if (emit(f->pending + start, i - start, arg) != 0) {
return -1;
}
start = i + 1;
}
}
memmove(f->pending, f->pending + start, end - start);
f->npending = end - start;
}
}
int follower_poll(struct follower *f, follow_emit emit, void *arg) {
if (f->fd >= 0) {
// Look at the path before the read. Then the read gets each byte that
// was written before a rename or a delete.
struct stat now, open_file;
int found = stat(f->path, &now) == 0;
if (!found && errno != ENOENT) {
return -1;
}
if (fstat(f->fd, &open_file) != 0) {
return -1;
}
if (open_file.st_size < f->offset) {
// The file is shorter than the offset, so it was truncated.
if (flush(f, emit, arg) != 0) {
return -1;
}
f->offset = 0;
}
if (read_new(f, emit, arg) != 0) {
return -1;
}
if (!found || now.st_dev != open_file.st_dev || now.st_ino != open_file.st_ino) {
// The file was deleted or renamed. Its rest is read.
close(f->fd);
f->fd = -1;
if (flush(f, emit, arg) != 0) {
return -1;
}
}
}
if (f->fd < 0) {
f->fd = open(f->path, O_RDONLY);
if (f->fd < 0) {
return errno == ENOENT ? 0 : -1;
}
f->offset = 0;
return read_new(f, emit, arg);
}
return 0;
}
int follower_follow(struct follower *f, unsigned interval_ms, int (*stop)(void *), follow_emit emit, void *arg) {
struct timespec interval = {.tv_sec = interval_ms / 1000, .tv_nsec = (long)(interval_ms % 1000) * 1000000};
for (;;) {
if (follower_poll(f, emit, arg) != 0) {
return -1;
}
if (stop(arg)) {
return 0;
}
nanosleep(&interval, NULL);
}
}
// Writes text to the file at path, which open opens with flags.
static int write_text(const char *path, int flags, const char *text) {
int fd = open(path, O_WRONLY | flags, 0644);
if (fd < 0) {
return -1;
}
size_t len = strlen(text);
while (len > 0) {
ssize_t n = write(fd, text, len);
if (n < 0 && errno == EINTR) {
continue;
}
if (n < 0) {
int e = errno;
close(fd);
errno = e;
return -1;
}
text += n;
len -= (size_t)n;
}
return close(fd);
}
// The polls of follow_file. The last string gets the lines of a poll.
struct polls {
char **items;
size_t n, len;
};
static int add_line(const char *line, size_t len, void *arg) {
struct polls *p = arg;
char *last = p->items[p->n - 1];
char *bigger = realloc(last, p->len + len + 2);
if (bigger == NULL) {
return -1;
}
memcpy(bigger + p->len, line, len);
bigger[p->len + len] = '\n';
bigger[p->len + len + 1] = '\0';
p->items[p->n - 1] = bigger;
p->len += len + 1;
return 0;
}
static int do_step(struct follower *f, const char *path, const char *old, const char *step, struct polls *p) {
const char *colon = strchr(step, ':');
size_t oplen = colon != NULL ? (size_t)(colon - step) : strlen(step);
const char *text = colon != NULL ? colon + 1 : "";
#define OP(name) (oplen == strlen(name) && strncmp(step, name, oplen) == 0)
if (OP("poll")) {
char **bigger = realloc(p->items, (p->n + 1) * sizeof *bigger);
if (bigger == NULL) {
return -1;
}
p->items = bigger;
p->items[p->n] = calloc(1, 1);
if (p->items[p->n] == NULL) {
return -1;
}
p->n++;
p->len = 0;
return follower_poll(f, add_line, p);
}
if (OP("append")) {
return write_text(path, O_CREAT | O_APPEND, text);
}
if (OP("append-old")) {
return write_text(old, O_CREAT | O_APPEND, text);
}
if (OP("truncate")) {
return write_text(path, O_CREAT | O_TRUNC, text);
}
if (OP("rotate")) {
return rename(path, old) != 0 ? -1 : write_text(path, O_CREAT | O_EXCL, "");
}
if (OP("delete")) {
return unlink(path);
}
if (OP("create")) {
return write_text(path, O_CREAT | O_EXCL, text);
}
#undef OP
errno = EINVAL;
return -1;
}
int follow_file(const char *path, const char *initial, const char *const steps[], char ***polls, size_t *npolls) {
if (write_text(path, O_CREAT | O_TRUNC, initial) != 0) {
return -1;
}
struct follower f;
if (follower_open(&f, path) != 0) {
return -1;
}
char *old = malloc(strlen(path) + 3);
struct polls p = {0};
int r = old == NULL ? -1 : 0;
if (old != NULL) {
strcpy(old, path);
strcat(old, ".1");
}
for (size_t i = 0; r == 0 && steps[i] != NULL; i++) {
r = do_step(&f, path, old, steps[i], &p);
}
int e = errno;
follower_close(&f);
free(old);
if (r != 0) {
for (size_t i = 0; i < p.n; i++) {
free(p.items[i]);
}
free(p.items);
errno = e;
return -1;
}
*polls = p.items;
*npolls = p.n;
return 0;
}
follow_file.h 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
#ifndef FOLLOW_FILE_H
#define FOLLOW_FILE_H
#include <stddef.h>
#include <sys/types.h>
// Reads the lines that are added to a file, one poll at a time, as tail -F
// does. The follower keeps the file open, so it can read the rest of the file
// after a rename or a delete.
struct follower {
char *path;
int fd; // -1 if no file is open
off_t offset;
char *pending; // the bytes after the last LF
size_t npending, cap;
};
// Gets one line, with no LF and no NUL at the end. Returns 0, or -1 with
// errno set to stop the poll.
typedef int (*follow_emit)(const char *line, size_t len, void *arg);
// Opens the file at path and starts at its end. Returns 0, or -1 with errno
// set. errno is ENOENT if no file is at path.
int follower_open(struct follower *f, const char *path);
// Calls emit with each complete line that was added since the last poll.
// Returns 0, or -1 with errno set.
int follower_poll(struct follower *f, follow_emit emit, void *arg);
// Calls follower_poll each interval_ms milliseconds, until stop returns
// nonzero. Returns 0, or -1 with errno set.
int follower_follow(struct follower *f, unsigned interval_ms, int (*stop)(void *), follow_emit emit, void *arg);
// Closes the file and frees the memory of the follower.
void follower_close(struct follower *f);
// Writes initial to path, makes a follower and does the steps, which end at a
// NULL. Each poll gives one string, with an LF after each line. Puts the
// strings in a new array in *polls, and their number in *npolls. The caller
// frees each string and the array. Returns 0, or -1 with errno set.
int follow_file(const char *path, const char *initial, const char *const steps[], char ***polls, size_t *npolls);
#endif
test_follow_file.c 177 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
#define _POSIX_C_SOURCE 200809L
#include "follow_file.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static int failures = 0;
#define CHECK(ok, name) \
do { \
if (!(ok)) { \
fprintf(stderr, "FAIL %s: line %d\n", name, __LINE__); \
failures++; \
} \
} while (0)
// Each poll is one string, with an LF after each line.
struct test_case {
const char *name, *initial;
const char *steps[9];
const char *want[4];
};
static const struct test_case cases[] = {
{"append-lines", "old\n", {"append:a\nb\n", "poll", "append:c\n", "poll", NULL}, {"a\nb\n", "c\n", NULL}},
{"partial-line", "", {"append:ab", "poll", "append:c\nd", "poll", "append:\n", "poll", NULL}, {"", "abc\n", "d\n", NULL}},
{"rotate", "1\n", {"append:2\n", "poll", "rotate", "append:3\n", "poll", NULL}, {"2\n", "3\n", NULL}},
{"truncate", "", {"append:a\nb\n", "poll", "truncate:", "poll", "append:c\n", "poll", NULL}, {"a\nb\n", "", "c\n", NULL}},
{"no-change", "x\n", {"poll", "poll", NULL}, {"", "", NULL}},
{"empty-line", "", {"append:\n\na\n", "poll", NULL}, {"\n\na\n", NULL}},
{"crlf", "", {"append:a\r\nb\r\n", "poll", NULL}, {"a\r\nb\r\n", NULL}},
{"truncate-and-write", "", {"append:aaaa\n", "poll", "truncate:b\n", "poll", NULL}, {"aaaa\n", "b\n", NULL}},
{"truncate-partial", "", {"append:abc", "poll", "truncate:d\n", "poll", NULL}, {"", "abc\nd\n", NULL}},
{"rotate-late-writes", "", {"append:1\n", "poll", "rotate", "append-old:2\n", "append:3\n", "poll", NULL}, {"1\n", "2\n3\n", NULL}},
{"rotate-partial", "", {"append:a", "poll", "rotate", "append:b\n", "poll", NULL}, {"", "a\nb\n", NULL}},
{"rotate-twice", "", {"append:1\n", "poll", "rotate", "append:2\n", "poll", "rotate", "append:3\n", "poll", NULL}, {"1\n", "2\n", "3\n", NULL}},
{"delete", "", {"append:1\n", "poll", "delete", "poll", "poll", NULL}, {"1\n", "", "", NULL}},
{"delete-partial", "", {"append:x", "poll", "delete", "poll", NULL}, {"", "x\n", NULL}},
{"delete-and-create", "", {"append:1\n", "poll", "delete", "poll", "create:2\n", "poll", NULL}, {"1\n", "", "2\n", NULL}},
{"delete-and-create-between-polls", "", {"append:1\n", "poll", "delete", "create:2\n", "poll", NULL}, {"1\n", "2\n", NULL}},
{"start-mid-line", "abc", {"append:d\ne\n", "poll", NULL}, {"d\ne\n", NULL}},
{"non-ascii", "", {"append:caf\303\251\nna\303\257ve\n", "poll", NULL}, {"caf\303\251\nna\303\257ve\n", NULL}},
};
static char dir[64], path[128], old[128];
static void free_polls(char **polls, size_t n) {
for (size_t i = 0; i < n; i++) {
free(polls[i]);
}
free(polls);
}
static void remove_files(void) {
unlink(path);
unlink(old);
}
// The lines and the polls of the follow test.
struct counts {
int lines, polls;
};
static int count_line(const char *line, size_t len, void *arg) {
(void)line;
(void)len;
((struct counts *)arg)->lines++;
return 0;
}
// Stop after 2 lines, or after 500 polls (5 seconds) if a line is lost.
static int two_lines(void *arg) {
struct counts *c = arg;
return c->lines >= 2 || ++c->polls > 500;
}
int main(void) {
// mkdtemp is not visible on all systems with _POSIX_C_SOURCE, so the test
// makes its own directory.
snprintf(dir, sizeof dir, "/tmp/follow-file-%ld", (long)getpid());
if (mkdir(dir, 0700) != 0) {
perror(dir);
return 1;
}
snprintf(path, sizeof path, "%s/followed.txt", dir);
snprintf(old, sizeof old, "%s/followed.txt.1", dir);
char **polls;
size_t n;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
int r = follow_file(path, c->initial, c->steps, &polls, &n);
CHECK(r == 0, c->name);
if (r == 0) {
size_t want = 0;
while (c->want[want] != NULL) {
want++;
}
CHECK(n == want, c->name);
for (size_t j = 0; j < n && j < want; j++) {
CHECK(strcmp(polls[j], c->want[j]) == 0, c->name);
}
free_polls(polls, n);
}
remove_files();
}
// not-found: no directory, so the first write fails.
char missing[160];
snprintf(missing, sizeof missing, "%s/missing/followed.txt", dir);
const char *poll[] = {"poll", NULL};
errno = 0;
CHECK(follow_file(missing, "", poll, &polls, &n) == -1 && errno == ENOENT, "not-found");
struct follower f;
errno = 0;
CHECK(follower_open(&f, missing) == -1 && errno == ENOENT, "not-found");
// 100000 lines in one poll.
size_t size = 0;
char *text = malloc(700000);
size += (size_t)snprintf(text, 8, "append:");
for (int i = 0; i < 100000; i++) {
size += (size_t)snprintf(text + size, 16, "%d\n", i);
}
const char *many[] = {text, "poll", NULL};
CHECK(follow_file(path, "", many, &polls, &n) == 0, "many-lines");
if (n == 1) {
size_t lines = 0;
for (const char *s = polls[0]; *s != '\0'; s++) {
lines += *s == '\n';
}
CHECK(lines == 100000, "many-lines");
CHECK(strncmp(polls[0], "0\n1\n", 4) == 0, "many-lines");
CHECK(strcmp(polls[0] + strlen(polls[0]) - 6, "99999\n") == 0, "many-lines");
free_polls(polls, n);
}
free(text);
remove_files();
// A character across two polls.
const char *split[] = {"append:caf\303", "poll", "append:\251\n", "poll", NULL};
CHECK(follow_file(path, "", split, &polls, &n) == 0, "character-across-polls");
if (n == 2) {
CHECK(strcmp(polls[0], "") == 0 && strcmp(polls[1], "caf\303\251\n") == 0, "character-across-polls");
free_polls(polls, n);
}
remove_files();
// follower_follow: the lines that come after the follower starts. The
// lines are written first, so that the test ends on its own.
const char *start[] = {"append:old\n", NULL};
CHECK(follow_file(path, "", start, &polls, &n) == 0, "follow");
free_polls(polls, n);
CHECK(follower_open(&f, path) == 0, "follow");
FILE *w = fopen(path, "ab");
fputs("a\nb\n", w);
fclose(w);
struct counts count = {0, 0};
CHECK(follower_follow(&f, 10, two_lines, count_line, &count) == 0 && count.lines == 2, "follow");
follower_close(&f);
remove_files();
rmdir(dir);
if (failures > 0) {
return 1;
}
printf("all tests pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
import fs from "node:fs";
// Follows a file that grows, as tail -F does, one poll at a time. The
// follower keeps the file open, so it can read the rest of the file after a
// rename or a delete. It starts at the end of the file. The constructor
// throws an error with the code ENOENT if no file is at path.
export class Follower {
constructor(path) {
this.path = path;
this.fd = fs.openSync(path, "r");
this.offset = fs.fstatSync(this.fd).size;
this.pending = Buffer.alloc(0); // the bytes after the last LF
}
// Returns the complete lines that were added since the last poll.
poll() {
const lines = [];
if (this.fd !== null) {
// Look at the path before the read. Then the read gets each byte that
// was written before a rename or a delete.
const now = fs.statSync(this.path, { bigint: true, throwIfNoEntry: false });
const open = fs.fstatSync(this.fd, { bigint: true });
if (open.size < BigInt(this.offset)) {
// The file is shorter than the offset, so it was truncated.
this.#flush(lines);
this.offset = 0;
}
this.#read(lines);
if (now === undefined || now.dev !== open.dev || now.ino !== open.ino) {
// The file was deleted or renamed. Its rest is read.
this.#flush(lines);
this.close();
}
}
if (this.fd === null) {
try {
this.fd = fs.openSync(this.path, "r");
} catch (err) {
if (err.code === "ENOENT") {
return lines;
}
throw err;
}
this.offset = 0;
this.#read(lines);
}
return lines;
}
close() {
if (this.fd !== null) {
fs.closeSync(this.fd);
this.fd = null;
}
}
#read(lines) {
const chunks = [this.pending];
const buf = Buffer.alloc(65536);
for (;;) {
const n = fs.readSync(this.fd, buf, 0, buf.length, this.offset);
if (n === 0) {
break;
}
chunks.push(Buffer.from(buf.subarray(0, n)));
this.offset += n;
}
// Split the bytes at each LF first, and decode each line after. A chunk
// can end in the middle of a UTF-8 character.
const data = Buffer.concat(chunks);
let start = 0;
for (let lf = data.indexOf(10); lf >= 0; lf = data.indexOf(10, start)) {
lines.push(data.toString("utf8", start, lf));
start = lf + 1;
}
this.pending = data.subarray(start);
}
#flush(lines) {
if (this.pending.length > 0) {
lines.push(this.pending.toString("utf8"));
this.pending = Buffer.alloc(0);
}
}
}
// Writes initial to path, makes a follower, does the steps and returns the
// lines of each poll.
export function followFile(path, initial, steps) {
fs.writeFileSync(path, initial);
const follower = new Follower(path);
const old = `${path}.1`;
const polls = [];
try {
for (const step of steps) {
const colon = step.indexOf(":");
const op = colon < 0 ? step : step.slice(0, colon);
const text = colon < 0 ? "" : step.slice(colon + 1);
if (op === "poll") {
polls.push(follower.poll());
} else if (op === "append") {
fs.appendFileSync(path, text);
} else if (op === "append-old") {
fs.appendFileSync(old, text);
} else if (op === "truncate") {
fs.writeFileSync(path, text);
} else if (op === "rotate") {
fs.renameSync(path, old);
fs.writeFileSync(path, "", { flag: "wx" });
} else if (op === "delete") {
fs.unlinkSync(path);
} else if (op === "create") {
fs.writeFileSync(path, text, { flag: "wx" });
} else {
throw new RangeError(`bad step: ${step}`);
}
}
} finally {
follower.close();
}
return polls;
}
followFile.test.js 74 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
import assert from "node:assert/strict";
import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { test } from "node:test";
import { Follower, followFile } from "./followFile.js";
const node = fileURLToPath(new URL("../../", import.meta.url));
function load(name) {
return readFileSync(join(node, "cases", name), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line));
}
function inTempDir(fn) {
const dir = mkdtempSync(join(tmpdir(), "follow-file-"));
try {
fn(dir);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
inTempDir((dir) => {
assert.deepEqual(followFile(join(dir, c.args.path), c.args.initial, c.args.steps), c.expect);
});
});
}
test("not-found", () => {
inTempDir((dir) => {
assert.throws(() => followFile(join(dir, "missing", "followed.txt"), "", ["poll"]), { code: "ENOENT" });
});
});
test("many-lines", () => {
inTempDir((dir) => {
const path = join(dir, "followed.txt");
writeFileSync(path, "");
const follower = new Follower(path);
let text = "";
for (let i = 0; i < 100000; i++) {
text += `${i}\n`;
}
appendFileSync(path, text);
const lines = follower.poll();
follower.close();
assert.equal(lines.length, 100000);
assert.equal(lines[0], "0");
assert.equal(lines.at(-1), "99999");
});
});
test("character-across-polls", () => {
inTempDir((dir) => {
const path = join(dir, "followed.txt");
writeFileSync(path, "");
const follower = new Follower(path);
// The two bytes of U+00E9 come in two polls.
appendFileSync(path, Buffer.from([0x63, 0x61, 0x66, 0xc3]));
assert.deepEqual(follower.poll(), []);
appendFileSync(path, Buffer.from([0xa9, 0x0a]));
assert.deepEqual(follower.poll(), ["caf\u00e9"]);
follower.close();
});
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
import fs from "node:fs";
// Follows a file that grows, as tail -F does, one poll at a time. The
// follower keeps the file open, so it can read the rest of the file after a
// rename or a delete. It starts at the end of the file. The constructor
// throws an error with the code ENOENT if no file is at path.
export class Follower {
path: string;
fd: number | null;
offset: number;
pending: Buffer; // the bytes after the last LF
constructor(path: string) {
this.path = path;
this.fd = fs.openSync(path, "r");
this.offset = fs.fstatSync(this.fd).size;
this.pending = Buffer.alloc(0);
}
// Returns the complete lines that were added since the last poll.
poll(): string[] {
const lines: string[] = [];
if (this.fd !== null) {
// Look at the path before the read. Then the read gets each byte that
// was written before a rename or a delete.
const now = fs.statSync(this.path, { bigint: true, throwIfNoEntry: false });
const open = fs.fstatSync(this.fd, { bigint: true });
if (open.size < BigInt(this.offset)) {
// The file is shorter than the offset, so it was truncated.
this.#flush(lines);
this.offset = 0;
}
this.#read(lines);
if (now === undefined || now.dev !== open.dev || now.ino !== open.ino) {
// The file was deleted or renamed. Its rest is read.
this.#flush(lines);
this.close();
}
}
if (this.fd === null) {
try {
this.fd = fs.openSync(this.path, "r");
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
return lines;
}
throw err;
}
this.offset = 0;
this.#read(lines);
}
return lines;
}
close(): void {
if (this.fd !== null) {
fs.closeSync(this.fd);
this.fd = null;
}
}
#read(lines: string[]): void {
const chunks = [this.pending];
const buf = Buffer.alloc(65536);
for (;;) {
const n = fs.readSync(this.fd as number, buf, 0, buf.length, this.offset);
if (n === 0) {
break;
}
chunks.push(Buffer.from(buf.subarray(0, n)));
this.offset += n;
}
// Split the bytes at each LF first, and decode each line after. A chunk
// can end in the middle of a UTF-8 character.
const data = Buffer.concat(chunks);
let start = 0;
for (let lf = data.indexOf(10); lf >= 0; lf = data.indexOf(10, start)) {
lines.push(data.toString("utf8", start, lf));
start = lf + 1;
}
this.pending = data.subarray(start);
}
#flush(lines: string[]): void {
if (this.pending.length > 0) {
lines.push(this.pending.toString("utf8"));
this.pending = Buffer.alloc(0);
}
}
}
// Writes initial to path, makes a follower, does the steps and returns the
// lines of each poll.
export function followFile(path: string, initial: string, steps: string[]): string[][] {
fs.writeFileSync(path, initial);
const follower = new Follower(path);
const old = `${path}.1`;
const polls: string[][] = [];
try {
for (const step of steps) {
const colon = step.indexOf(":");
const op = colon < 0 ? step : step.slice(0, colon);
const text = colon < 0 ? "" : step.slice(colon + 1);
if (op === "poll") {
polls.push(follower.poll());
} else if (op === "append") {
fs.appendFileSync(path, text);
} else if (op === "append-old") {
fs.appendFileSync(old, text);
} else if (op === "truncate") {
fs.writeFileSync(path, text);
} else if (op === "rotate") {
fs.renameSync(path, old);
fs.writeFileSync(path, "", { flag: "wx" });
} else if (op === "delete") {
fs.unlinkSync(path);
} else if (op === "create") {
fs.writeFileSync(path, text, { flag: "wx" });
} else {
throw new RangeError(`bad step: ${step}`);
}
}
} finally {
follower.close();
}
return polls;
}
followFile.test.ts 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
import assert from "node:assert/strict";
import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { test } from "node:test";
import { Follower, followFile } from "./followFile.ts";
interface Case {
name: string;
args: { path: string; initial: string; steps: string[] };
expect: string[][];
}
const node = fileURLToPath(new URL("../../", import.meta.url));
function load(name: string): Case[] {
return readFileSync(join(node, "cases", name), "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line) as Case);
}
function inTempDir(fn: (dir: string) => void): void {
const dir = mkdtempSync(join(tmpdir(), "follow-file-"));
try {
fn(dir);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
for (const c of [...load("basic.jsonl"), ...load("edge.jsonl")]) {
test(c.name, () => {
inTempDir((dir) => {
assert.deepEqual(followFile(join(dir, c.args.path), c.args.initial, c.args.steps), c.expect);
});
});
}
test("not-found", () => {
inTempDir((dir) => {
assert.throws(() => followFile(join(dir, "missing", "followed.txt"), "", ["poll"]), { code: "ENOENT" });
});
});
test("many-lines", () => {
inTempDir((dir) => {
const path = join(dir, "followed.txt");
writeFileSync(path, "");
const follower = new Follower(path);
let text = "";
for (let i = 0; i < 100000; i++) {
text += `${i}\n`;
}
appendFileSync(path, text);
const lines = follower.poll();
follower.close();
assert.equal(lines.length, 100000);
assert.equal(lines[0], "0");
assert.equal(lines.at(-1), "99999");
});
});
test("character-across-polls", () => {
inTempDir((dir) => {
const path = join(dir, "followed.txt");
writeFileSync(path, "");
const follower = new Follower(path);
// The two bytes of U+00E9 come in two polls.
appendFileSync(path, Buffer.from([0x63, 0x61, 0x66, 0xc3]));
assert.deepEqual(follower.poll(), []);
appendFileSync(path, Buffer.from([0xa9, 0x0a]));
assert.deepEqual(follower.poll(), ["caf\u00e9"]);
follower.close();
});
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
// Package followfile follows a file that grows, as tail -F does.
package followfile
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"strings"
"time"
)
// A Follower reads the lines that are added to a file, one poll at a time.
// It keeps the file open, so it can read the rest of the file after a rename
// or a delete.
type Follower struct {
path string
f *os.File // nil if no file is open
offset int64
pending []byte // the bytes after the last LF
}
// NewFollower opens the file at path and starts at its end. The error is
// fs.ErrNotExist if no file is at path.
func NewFollower(path string) (*Follower, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
info, err := f.Stat()
if err != nil {
f.Close()
return nil, err
}
return &Follower{path: path, f: f, offset: info.Size()}, nil
}
// Poll returns the complete lines that were added since the last poll.
func (fl *Follower) Poll() ([]string, error) {
var lines []string
if fl.f != nil {
// Look at the path before the read. Then the read gets each byte that
// was written before a rename or a delete.
now, err := os.Stat(fl.path)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, err
}
open, err := fl.f.Stat()
if err != nil {
return nil, err
}
if open.Size() < fl.offset {
// The file is shorter than the offset, so it was truncated.
lines = fl.flush(lines)
fl.offset = 0
}
if lines, err = fl.read(lines); err != nil {
return nil, err
}
if now == nil || !os.SameFile(now, open) {
// The file was deleted or renamed. Its rest is read.
lines = fl.flush(lines)
fl.Close()
}
}
if fl.f == nil {
f, err := os.Open(fl.path)
if errors.Is(err, fs.ErrNotExist) {
return lines, nil
}
if err != nil {
return nil, err
}
fl.f, fl.offset = f, 0
return fl.read(lines)
}
return lines, nil
}
// Close closes the file.
func (fl *Follower) Close() error {
if fl.f == nil {
return nil
}
err := fl.f.Close()
fl.f = nil
return err
}
func (fl *Follower) read(lines []string) ([]string, error) {
buf := make([]byte, 65536)
for {
n, err := fl.f.ReadAt(buf, fl.offset)
fl.pending = append(fl.pending, buf[:n]...)
fl.offset += int64(n)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
// Split the bytes at each LF.
start := 0
for {
lf := bytes.IndexByte(fl.pending[start:], '\n')
if lf < 0 {
break
}
lines = append(lines, string(fl.pending[start:start+lf]))
start += lf + 1
}
fl.pending = append([]byte(nil), fl.pending[start:]...)
return lines, nil
}
func (fl *Follower) flush(lines []string) []string {
if len(fl.pending) > 0 {
lines = append(lines, string(fl.pending))
fl.pending = nil
}
return lines
}
// Follow calls emit with each new line. It polls the file each interval, and
// returns when stop is closed. Make the follower before the goroutine that
// calls Follow: the follower starts at the end of the file when it is made.
func (fl *Follower) Follow(interval time.Duration, stop <-chan struct{}, emit func(string)) error {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
lines, err := fl.Poll()
if err != nil {
return err
}
for _, line := range lines {
emit(line)
}
select {
case <-stop:
return nil
case <-ticker.C:
}
}
}
// FollowFile writes initial to path, makes a follower, does the steps and
// returns the lines of each poll.
func FollowFile(path, initial string, steps []string) ([][]string, error) {
if err := os.WriteFile(path, []byte(initial), 0o644); err != nil {
return nil, err
}
fl, err := NewFollower(path)
if err != nil {
return nil, err
}
defer fl.Close()
old := path + ".1"
polls := [][]string{}
for _, step := range steps {
op, text, _ := strings.Cut(step, ":")
switch op {
case "poll":
lines, err := fl.Poll()
if err != nil {
return nil, err
}
polls = append(polls, lines)
case "append", "append-old":
name := path
if op == "append-old" {
name = old
}
err = appendFile(name, text)
case "truncate":
err = os.WriteFile(path, []byte(text), 0o644)
case "rotate":
if err = os.Rename(path, old); err == nil {
err = createFile(path, "")
}
case "delete":
err = os.Remove(path)
case "create":
err = createFile(path, text)
default:
err = fmt.Errorf("bad step: %q", step)
}
if err != nil {
return nil, err
}
}
return polls, nil
}
func appendFile(name, text string) error {
f, err := os.OpenFile(name, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o644)
if err != nil {
return err
}
_, err = f.WriteString(text)
return errors.Join(err, f.Close())
}
func createFile(name, text string) error {
f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if err != nil {
return err
}
_, err = f.WriteString(text)
return errors.Join(err, f.Close())
}
follow_file_test.go 130 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
package followfile
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)
var cases = []struct {
name, initial string
steps []string
want [][]string
}{
{"append-lines", "old\n", []string{"append:a\nb\n", "poll", "append:c\n", "poll"}, [][]string{{"a", "b"}, {"c"}}},
{"partial-line", "", []string{"append:ab", "poll", "append:c\nd", "poll", "append:\n", "poll"}, [][]string{{}, {"abc"}, {"d"}}},
{"rotate", "1\n", []string{"append:2\n", "poll", "rotate", "append:3\n", "poll"}, [][]string{{"2"}, {"3"}}},
{"truncate", "", []string{"append:a\nb\n", "poll", "truncate:", "poll", "append:c\n", "poll"}, [][]string{{"a", "b"}, {}, {"c"}}},
{"no-change", "x\n", []string{"poll", "poll"}, [][]string{{}, {}}},
{"empty-line", "", []string{"append:\n\na\n", "poll"}, [][]string{{"", "", "a"}}},
{"crlf", "", []string{"append:a\r\nb\r\n", "poll"}, [][]string{{"a\r", "b\r"}}},
{"truncate-and-write", "", []string{"append:aaaa\n", "poll", "truncate:b\n", "poll"}, [][]string{{"aaaa"}, {"b"}}},
{"truncate-partial", "", []string{"append:abc", "poll", "truncate:d\n", "poll"}, [][]string{{}, {"abc", "d"}}},
{"rotate-late-writes", "", []string{"append:1\n", "poll", "rotate", "append-old:2\n", "append:3\n", "poll"}, [][]string{{"1"}, {"2", "3"}}},
{"rotate-partial", "", []string{"append:a", "poll", "rotate", "append:b\n", "poll"}, [][]string{{}, {"a", "b"}}},
{"rotate-twice", "", []string{"append:1\n", "poll", "rotate", "append:2\n", "poll", "rotate", "append:3\n", "poll"}, [][]string{{"1"}, {"2"}, {"3"}}},
{"delete", "", []string{"append:1\n", "poll", "delete", "poll", "poll"}, [][]string{{"1"}, {}, {}}},
{"delete-partial", "", []string{"append:x", "poll", "delete", "poll"}, [][]string{{}, {"x"}}},
{"delete-and-create", "", []string{"append:1\n", "poll", "delete", "poll", "create:2\n", "poll"}, [][]string{{"1"}, {}, {"2"}}},
{"delete-and-create-between-polls", "", []string{"append:1\n", "poll", "delete", "create:2\n", "poll"}, [][]string{{"1"}, {"2"}}},
{"start-mid-line", "abc", []string{"append:d\ne\n", "poll"}, [][]string{{"d", "e"}}},
{"non-ascii", "", []string{"append:caf\u00e9\nna\u00efve\n", "poll"}, [][]string{{"caf\u00e9", "na\u00efve"}}},
}
func TestFollowFile(t *testing.T) {
for _, c := range cases {
got, err := FollowFile(filepath.Join(t.TempDir(), "followed.txt"), c.initial, c.steps)
if err != nil {
t.Errorf("%s: %v", c.name, err)
continue
}
// An empty poll is nil in got and empty in want.
for i := range got {
if got[i] == nil {
got[i] = []string{}
}
}
if !reflect.DeepEqual(got, c.want) {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestNotFound(t *testing.T) {
_, err := FollowFile(filepath.Join(t.TempDir(), "missing", "followed.txt"), "", []string{"poll"})
if !errors.Is(err, fs.ErrNotExist) {
t.Errorf("got %v, want fs.ErrNotExist", err)
}
if _, err := NewFollower(filepath.Join(t.TempDir(), "missing.txt")); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("got %v, want fs.ErrNotExist", err)
}
}
func TestManyLines(t *testing.T) {
var b strings.Builder
for i := range 100000 {
fmt.Fprintf(&b, "%d\n", i)
}
got, err := FollowFile(filepath.Join(t.TempDir(), "followed.txt"), "", []string{"append:" + b.String(), "poll"})
if err != nil {
t.Fatal(err)
}
lines := got[0]
if len(lines) != 100000 || lines[0] != "0" || lines[99999] != "99999" {
t.Errorf("got %d lines", len(lines))
}
}
func TestCharacterAcrossPolls(t *testing.T) {
path := filepath.Join(t.TempDir(), "followed.txt")
got, err := FollowFile(path, "", []string{"append:caf\xc3", "poll", "append:\xa9\n", "poll"})
if err != nil {
t.Fatal(err)
}
if len(got[0]) != 0 || !reflect.DeepEqual(got[1], []string{"café"}) {
t.Errorf("got %q", got)
}
}
func TestFollow(t *testing.T) {
path := filepath.Join(t.TempDir(), "followed.txt")
if err := os.WriteFile(path, []byte("old\n"), 0o644); err != nil {
t.Fatal(err)
}
fl, err := NewFollower(path)
if err != nil {
t.Fatal(err)
}
defer fl.Close()
stop := make(chan struct{})
done := make(chan error)
var lines []string
go func() {
done <- fl.Follow(10*time.Millisecond, stop, func(line string) {
lines = append(lines, line)
if len(lines) == 2 {
close(stop)
}
})
}()
if err := appendFile(path, "a\nb\n"); err != nil {
t.Fatal(err)
}
select {
case err := <-done:
if err != nil || !reflect.DeepEqual(lines, []string{"a", "b"}) {
t.Errorf("got %q, %v", lines, err)
}
case <-time.After(5 * time.Second):
t.Fatal("no lines after 5 seconds")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
//! Follows a file that grows, as tail -F does.
use std::fs::{self, File, OpenOptions};
use std::io::{self, ErrorKind, Read, Seek, SeekFrom, Write};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::Duration;
/// Reads the lines that are added to a file, one poll at a time. The follower
/// keeps the file open, so it can read the rest of the file after a rename or
/// a delete.
pub struct Follower {
path: PathBuf,
file: Option<File>,
offset: u64,
/// The bytes after the last LF.
pending: Vec<u8>,
}
impl Follower {
/// Opens the file at path and starts at its end. The error kind is
/// NotFound if no file is at path.
pub fn new(path: impl AsRef<Path>) -> io::Result<Follower> {
let path = path.as_ref().to_path_buf();
let file = File::open(&path)?;
let offset = file.metadata()?.len();
Ok(Follower {
path,
file: Some(file),
offset,
pending: Vec::new(),
})
}
/// Returns the complete lines that were added since the last poll.
pub fn poll(&mut self) -> io::Result<Vec<String>> {
let mut lines = Vec::new();
// Look at the path before the read. Then the read gets each byte that
// was written before a rename or a delete.
let now = not_found_is_none(fs::metadata(&self.path))?;
if let Some(open) = self.file.as_ref().map(File::metadata).transpose()? {
if open.len() < self.offset {
// The file is shorter than the offset, so it was truncated.
self.flush(&mut lines);
self.offset = 0;
}
self.read(&mut lines)?;
let same = now.is_some_and(|now| now.dev() == open.dev() && now.ino() == open.ino());
if !same {
// The file was deleted or renamed. Its rest is read.
self.flush(&mut lines);
self.file = None;
}
}
if self.file.is_none() {
if let Some(file) = not_found_is_none(File::open(&self.path))? {
self.file = Some(file);
self.offset = 0;
self.read(&mut lines)?;
}
}
Ok(lines)
}
/// Calls emit with each new line. Polls the file each interval, and
/// returns when stop returns true.
pub fn follow(
&mut self,
interval: Duration,
mut stop: impl FnMut() -> bool,
mut emit: impl FnMut(String),
) -> io::Result<()> {
loop {
for line in self.poll()? {
emit(line);
}
if stop() {
return Ok(());
}
thread::sleep(interval);
}
}
fn read(&mut self, lines: &mut Vec<String>) -> io::Result<()> {
let Some(file) = self.file.as_mut() else {
return Ok(());
};
file.seek(SeekFrom::Start(self.offset))?;
let n = file.read_to_end(&mut self.pending)?;
self.offset += n as u64;
// Split the bytes at each LF first, and decode each line after. A
// read can end in the middle of a UTF-8 character.
let mut start = 0;
while let Some(lf) = self.pending[start..].iter().position(|&b| b == b'\n') {
lines.push(String::from_utf8_lossy(&self.pending[start..start + lf]).into_owned());
start += lf + 1;
}
self.pending.drain(..start);
Ok(())
}
fn flush(&mut self, lines: &mut Vec<String>) {
if !self.pending.is_empty() {
lines.push(String::from_utf8_lossy(&self.pending).into_owned());
self.pending.clear();
}
}
}
fn not_found_is_none<T>(result: io::Result<T>) -> io::Result<Option<T>> {
match result {
Ok(value) => Ok(Some(value)),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
/// Writes initial to path, makes a follower, does the steps and returns the
/// lines of each poll.
pub fn follow_file(
path: impl AsRef<Path>,
initial: &str,
steps: &[&str],
) -> io::Result<Vec<Vec<String>>> {
let path = path.as_ref();
fs::write(path, initial)?;
let mut follower = Follower::new(path)?;
let mut old = path.as_os_str().to_owned();
old.push(".1");
let mut polls = Vec::new();
for step in steps {
let (op, text) = step.split_once(':').unwrap_or((step, ""));
match op {
"poll" => polls.push(follower.poll()?),
"append" => append(path, text)?,
"append-old" => append(Path::new(&old), text)?,
"truncate" => fs::write(path, text)?,
"rotate" => {
fs::rename(path, &old)?;
create(path, "")?;
}
"delete" => fs::remove_file(path)?,
"create" => create(path, text)?,
_ => {
return Err(io::Error::new(
ErrorKind::InvalidInput,
format!("bad step: {step:?}"),
))
}
}
}
Ok(polls)
}
fn append(path: &Path, text: &str) -> io::Result<()> {
OpenOptions::new()
.append(true)
.create(true)
.open(path)?
.write_all(text.as_bytes())
}
fn create(path: &Path, text: &str) -> io::Result<()> {
OpenOptions::new()
.write(true)
.create_new(true)
.open(path)?
.write_all(text.as_bytes())
}
tests/follow_file_test.rs 237 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/tail-a-growing-file/.
use std::cell::Cell;
use std::fs::{self, OpenOptions};
use std::io::{ErrorKind, Write};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use algo_follow_file::{follow_file, Follower};
/// (name, initial, steps, the lines of each poll)
type Case<'a> = (&'a str, &'a str, &'a [&'a str], &'a [&'a [&'a str]]);
/// Makes a new directory for one test.
fn temp_dir() -> PathBuf {
static NEXT: AtomicU32 = AtomicU32::new(0);
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("follow-file-{}-{n}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
dir
}
const CASES: &[Case] = &[
(
"append-lines",
"old\n",
&["append:a\nb\n", "poll", "append:c\n", "poll"],
&[&["a", "b"], &["c"]],
),
(
"partial-line",
"",
&[
"append:ab",
"poll",
"append:c\nd",
"poll",
"append:\n",
"poll",
],
&[&[], &["abc"], &["d"]],
),
(
"rotate",
"1\n",
&["append:2\n", "poll", "rotate", "append:3\n", "poll"],
&[&["2"], &["3"]],
),
(
"truncate",
"",
&[
"append:a\nb\n",
"poll",
"truncate:",
"poll",
"append:c\n",
"poll",
],
&[&["a", "b"], &[], &["c"]],
),
("no-change", "x\n", &["poll", "poll"], &[&[], &[]]),
(
"empty-line",
"",
&["append:\n\na\n", "poll"],
&[&["", "", "a"]],
),
(
"crlf",
"",
&["append:a\r\nb\r\n", "poll"],
&[&["a\r", "b\r"]],
),
(
"truncate-and-write",
"",
&["append:aaaa\n", "poll", "truncate:b\n", "poll"],
&[&["aaaa"], &["b"]],
),
(
"truncate-partial",
"",
&["append:abc", "poll", "truncate:d\n", "poll"],
&[&[], &["abc", "d"]],
),
(
"rotate-late-writes",
"",
&[
"append:1\n",
"poll",
"rotate",
"append-old:2\n",
"append:3\n",
"poll",
],
&[&["1"], &["2", "3"]],
),
(
"rotate-partial",
"",
&["append:a", "poll", "rotate", "append:b\n", "poll"],
&[&[], &["a", "b"]],
),
(
"rotate-twice",
"",
&[
"append:1\n",
"poll",
"rotate",
"append:2\n",
"poll",
"rotate",
"append:3\n",
"poll",
],
&[&["1"], &["2"], &["3"]],
),
(
"delete",
"",
&["append:1\n", "poll", "delete", "poll", "poll"],
&[&["1"], &[], &[]],
),
(
"delete-partial",
"",
&["append:x", "poll", "delete", "poll"],
&[&[], &["x"]],
),
(
"delete-and-create",
"",
&["append:1\n", "poll", "delete", "poll", "create:2\n", "poll"],
&[&["1"], &[], &["2"]],
),
(
"delete-and-create-between-polls",
"",
&["append:1\n", "poll", "delete", "create:2\n", "poll"],
&[&["1"], &["2"]],
),
(
"start-mid-line",
"abc",
&["append:d\ne\n", "poll"],
&[&["d", "e"]],
),
(
"non-ascii",
"",
&["append:caf\u{e9}\nna\u{ef}ve\n", "poll"],
&[&["caf\u{e9}", "na\u{ef}ve"]],
),
];
#[test]
fn cases() {
for (name, initial, steps, want) in CASES {
let dir = temp_dir();
let got = follow_file(dir.join("followed.txt"), initial, steps).unwrap();
assert_eq!(got, *want, "{name}");
fs::remove_dir_all(&dir).unwrap();
}
}
#[test]
fn not_found() {
let dir = temp_dir();
let err = follow_file(dir.join("missing").join("followed.txt"), "", &["poll"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
let err = Follower::new(dir.join("missing.txt")).err().unwrap();
assert_eq!(err.kind(), ErrorKind::NotFound);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn many_lines() {
let dir = temp_dir();
let text: String = (0..100000).map(|i| format!("{i}\n")).collect();
let step = format!("append:{text}");
let got = follow_file(dir.join("followed.txt"), "", &[&step, "poll"]).unwrap();
assert_eq!(got[0].len(), 100000);
assert_eq!(got[0][0], "0");
assert_eq!(got[0][99999], "99999");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn character_across_polls() {
let dir = temp_dir();
let path = dir.join("followed.txt");
fs::write(&path, "").unwrap();
let mut follower = Follower::new(&path).unwrap();
let mut file = OpenOptions::new().append(true).open(&path).unwrap();
file.write_all(b"caf\xc3").unwrap();
assert!(follower.poll().unwrap().is_empty());
file.write_all(b"\xa9\n").unwrap();
assert_eq!(follower.poll().unwrap(), ["caf\u{e9}"]);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn follow() {
let dir = temp_dir();
let path = dir.join("followed.txt");
fs::write(&path, "old\n").unwrap();
let mut follower = Follower::new(&path).unwrap();
// Write the lines first, so that the test ends on its own.
OpenOptions::new()
.append(true)
.open(&path)
.unwrap()
.write_all(b"a\nb\n")
.unwrap();
// Stop after 2 lines, or after 500 polls (5 seconds) if a line is lost.
let count = Cell::new(0);
let mut polls = 0;
let mut lines = Vec::new();
let stop = || {
polls += 1;
count.get() >= 2 || polls > 500
};
let emit = |line| {
lines.push(line);
count.set(count.get() + 1);
};
follower
.follow(Duration::from_millis(10), stop, emit)
.unwrap();
assert_eq!(lines, ["a", "b"]);
fs::remove_dir_all(&dir).unwrap();
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/tail-a-growing-file/.
# A follower reads the lines that are added to a file, one poll at a time, as
# tail -F does. It keeps the file open on file descriptor 9, so it can read
# the rest of the file after a rename or a delete. The state is in global
# variables, so a shell has one follower, and follow_poll must run in the
# shell itself: call it as follow_poll > out, not as $(follow_poll) or in a
# pipeline. Bash cannot get the inode number of an open file, so the follower
# takes it from the path just after the open. A NUL byte in the file is lost.
_follow_path= _follow_open=0 _follow_inode= _follow_offset=0 _follow_pending=
follow_count=0 # the number of lines of the last poll
# Prints the inode number of the file at $1, or fails if no file is there.
_follow_inode_of() {
local out
out=$(ls -di -- "$1" 2>/dev/null) || return 1
set -- $out
printf '%s\n' "$1"
}
# follow_open PATH: opens the file at PATH and starts at its end. Fails if no
# file is at PATH.
follow_open() {
local LC_ALL=C
follow_close
{ exec 9<"$1"; } 2>/dev/null || {
printf 'follow_open: %s: cannot open\n' "$1" >&2
return 1
}
_follow_path=$1 _follow_open=1 _follow_pending=
_follow_inode=$(_follow_inode_of "$1") || { follow_close; return 1; }
# Read to the end of the file, and count the bytes.
_follow_offset=$(cat <&9 | wc -c) || { follow_close; return 1; }
_follow_offset=$((_follow_offset))
}
# follow_poll: prints the complete lines that were added since the last poll,
# each with an LF, and puts their number in follow_count.
follow_poll() {
local LC_ALL=C now size
follow_count=0
if [ "$_follow_open" = 1 ]; then
# Look at the path before the read. Then the read gets each byte that was
# written before a rename or a delete.
now=$(_follow_inode_of "$_follow_path") || now=
if [ "$now" = "$_follow_inode" ]; then
size=$(wc -c < "$_follow_path") || return 1
if [ $((size)) -lt "$_follow_offset" ]; then
# The file is shorter than the offset, so it was truncated. Bash
# cannot seek, so the follower opens the file again.
_follow_flush
exec 9<"$_follow_path" || return 1
_follow_offset=0
fi
fi
_follow_read
if [ "$now" != "$_follow_inode" ]; then
# The file was deleted or renamed. Its rest is read.
_follow_flush
follow_close
fi
fi
if [ "$_follow_open" = 0 ] && [ -n "$_follow_path" ]; then
{ exec 9<"$_follow_path"; } 2>/dev/null || return 0
_follow_open=1 _follow_offset=0
_follow_inode=$(_follow_inode_of "$_follow_path") || _follow_inode=
_follow_read
fi
}
# Prints each complete line from fd 9. read gets the bytes after the last LF
# as a line with no LF, and they wait in _follow_pending for the next poll.
_follow_read() {
local line
while IFS= read -r -u 9 line; do
printf '%s%s\n' "$_follow_pending" "$line"
_follow_offset=$((_follow_offset + ${#line} + 1))
_follow_pending=
follow_count=$((follow_count + 1))
done
_follow_offset=$((_follow_offset + ${#line}))
_follow_pending=$_follow_pending$line
}
_follow_flush() {
if [ -n "$_follow_pending" ]; then
printf '%s\n' "$_follow_pending"
_follow_pending=
follow_count=$((follow_count + 1))
fi
}
# follow_close: closes the file.
follow_close() {
if [ "$_follow_open" = 1 ]; then
exec 9<&-
_follow_open=0
fi
}
# follow COUNT [SECONDS]: polls the follower each SECONDS (1 if not given)
# and prints the new lines. Returns after COUNT lines or more.
follow() {
local left=$1
while :; do
follow_poll || return 1
left=$((left - follow_count))
[ "$left" -gt 0 ] || return 0
sleep "${2:-1}"
done
}
# follow_file PATH INITIAL STEP...: writes INITIAL to PATH, opens a follower
# and does the steps. Prints N:LINE for each line of poll N.
follow_file() {
local path=$1 old=$1.1 step text n=0 tmp rc=0
printf '%s' "$2" > "$path" || return 1
follow_open "$path" || return 1
tmp=$(mktemp) || { follow_close; return 1; }
shift 2
for step; do
case $step in
*:*) text=${step#*:} ;;
*) text= ;;
esac
case ${step%%:*} in
poll) n=$((n + 1)) && follow_poll > "$tmp" && LC_ALL=C sed "s/^/$n:/" "$tmp" ;;
append) printf '%s' "$text" >> "$path" ;;
append-old) printf '%s' "$text" >> "$old" ;;
truncate) printf '%s' "$text" > "$path" ;;
rotate) mv -f -- "$path" "$old" && (set -C; : > "$path") ;;
delete) rm -f -- "$path" ;;
create) (set -C; printf '%s' "$text" > "$path") ;;
*) printf 'follow_file: bad step: %s\n' "$step" >&2; false ;;
esac || { rc=1; break; }
done
rm -f -- "$tmp"
follow_close
return "$rc"
}
test_follow_file.bats 63 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/tail-a-growing-file/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/follow_file.sh"
f=$BATS_TEST_TMPDIR/followed.txt
}
check() { # check WANT INITIAL STEP...: WANT has N:LINE for each line of poll N
local want=$1
shift
# The x keeps a final LF, which $(...) removes.
[ "$(follow_file "$f" "$@"; printf x)" = "${want}x" ]
}
@test "append-lines" { check $'1:a\n1:b\n2:c\n' $'old\n' $'append:a\nb\n' poll $'append:c\n' poll; }
@test "partial-line" { check $'2:abc\n3:d\n' '' $'append:ab' poll $'append:c\nd' poll $'append:\n' poll; }
@test "rotate" { check $'1:2\n2:3\n' $'1\n' $'append:2\n' poll rotate $'append:3\n' poll; }
@test "truncate" { check $'1:a\n1:b\n3:c\n' '' $'append:a\nb\n' poll $'truncate:' poll $'append:c\n' poll; }
@test "no-change" { check '' $'x\n' poll poll; }
@test "empty-line" { check $'1:\n1:\n1:a\n' '' $'append:\n\na\n' poll; }
@test "crlf" { check $'1:a\r\n1:b\r\n' '' $'append:a\r\nb\r\n' poll; }
@test "truncate-and-write" { check $'1:aaaa\n2:b\n' '' $'append:aaaa\n' poll $'truncate:b\n' poll; }
@test "truncate-partial" { check $'2:abc\n2:d\n' '' $'append:abc' poll $'truncate:d\n' poll; }
@test "rotate-late-writes" { check $'1:1\n2:2\n2:3\n' '' $'append:1\n' poll rotate $'append-old:2\n' $'append:3\n' poll; }
@test "rotate-partial" { check $'2:a\n2:b\n' '' $'append:a' poll rotate $'append:b\n' poll; }
@test "rotate-twice" { check $'1:1\n2:2\n3:3\n' '' $'append:1\n' poll rotate $'append:2\n' poll rotate $'append:3\n' poll; }
@test "delete" { check $'1:1\n' '' $'append:1\n' poll delete poll poll; }
@test "delete-partial" { check $'2:x\n' '' $'append:x' poll delete poll; }
@test "delete-and-create" { check $'1:1\n3:2\n' '' $'append:1\n' poll delete poll $'create:2\n' poll; }
@test "delete-and-create-between-polls" { check $'1:1\n2:2\n' '' $'append:1\n' poll delete $'create:2\n' poll; }
@test "start-mid-line" { check $'1:d\n1:e\n' abc $'append:d\ne\n' poll; }
@test "non-ascii" { check $'1:caf\303\251\n1:na\303\257ve\n' '' $'append:caf\303\251\nna\303\257ve\n' poll; }
@test "character-across-polls" { check $'2:caf\303\251\n' '' $'append:caf\303' poll $'append:\251\n' poll; }
@test "not-found" {
run follow_file "$BATS_TEST_TMPDIR/missing/followed.txt" '' poll
[ "$status" -ne 0 ]
run follow_open "$BATS_TEST_TMPDIR/missing.txt"
[ "$status" -ne 0 ]
}
@test "many-lines" {
# A new shell runs the follower, because the DEBUG trap of bats makes a
# loop of 100000 lines too slow.
out=$(bash -c '. "$1" && follow_file "$2" "" "append:$(seq 0 99999)
" poll' bash "$BATS_TEST_DIRNAME/follow_file.sh" "$f")
[ "$(printf '%s\n' "$out" | wc -l)" -eq 100000 ]
[ "$(printf '%s\n' "$out" | head -n 1)" = 1:0 ]
[ "$(printf '%s\n' "$out" | tail -n 1)" = 1:99999 ]
}
@test "follow" {
# The lines are written first, so that the test ends on its own.
printf 'old\n' > "$f"
follow_open "$f"
printf 'a\nb\n' >> "$f"
[ "$(follow 2 0.1)" = $'a\nb' ]
follow_close
}
References
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), tail, OPTIONS (-f)
- GNU Coreutils manual, tail invocation, -f, --follow; -F; --retry
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), sys/stat.h, DESCRIPTION; RATIONALE
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), fstat, DESCRIPTION
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), pread, read, DESCRIPTION
- .NET API reference, FileSystemInfo, Properties
- The Python Standard Library, os.path, samestat
- Node.js documentation, File system, fs.statSync; fs.readSync; fs.Stats
- Java SE 25 API, java.nio.channels.FileChannel, read(ByteBuffer, long); size
- Java SE 25 API, java.nio.file.attribute.BasicFileAttributes, fileKey
- Go standard library, package os, SameFile; File.ReadAt
- The Rust Standard Library, std::os::unix::fs::MetadataExt, dev; ino
- GNU Bash manual, Bash Builtin Commands, read
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), ls, OPTIONS (-i); STDOUT
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), rename, renameat, DESCRIPTION
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), open, openat, DESCRIPTION (O_TRUNC)
- Node.js documentation, String decoder, Class StringDecoder
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), unlink, unlinkat, DESCRIPTION
- Linux manual page, inotify(7), DESCRIPTION; NOTES (Limitations and caveats)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 09XWYW Edit this page History Report an error Markdown