File too large errno 27: RLIMIT_FSIZE, SIGXFSZ, and the bytes that fit

Dark cover headed 'File too large': errno 27, a 4,096-byte limit that stored 4,096 bytes of a 5,000-byte write, SIGXFSZ as signal 25, shell status 153, and 36 passing tests
  • errno 27 is not a full disk. It is a per-process ceiling on how large one file may grow (RLIMIT_FSIZE), and the ceiling can be 4,096 bytes on a host with gigabytes free.
  • A write that asks for more than the ceiling is cut, not refused. At a 4,096-byte limit, one 5,000-byte write stored 4,096 bytes and returned 4,096; the next write began at the limit, so the kernel sent SIGXFSZ (25) and returned EFBIG.
  • The signal decides whether you see anything, and Python has already answered it. The kernel’s default action ends the process: shell status 153, no traceback, nothing on stderr – which is what a C program gets, because it begins at that default; dd died this way five times out of five. CPython sets SIGXFSZ to SIG_IGN while it starts, so the same write in Python raises OSError: [Errno 27] instead.
  • Check three things in this order: the count a write returned, the row Max file size in /proc/<pid>/limits, and the exit status 153. Only the third one is visible after the process is gone.

Fix It First: Ten Changes, Matched to What You Saw

Each row starts from something an operator actually sees – a truncated log, a worker that vanished with no traceback, a copy that stopped at a round number – and names the one change that turns it into an answer. Every figure in the table was measured on the host described in Section 2 unless the row says otherwise.

What you sawChangeWhy it works
A log ends at a round number of bytes, with no error in itCheck the count each write returns, not just that it returnedA write past the ceiling is cut short and reports success; the number it returns is the only sign
A worker or container died with no traceback and no OOM recordTreat exit status 153 (128+25) as SIGXFSZ, not OOMThe kernel’s default action ends the process before the call returns; pure Python ignores the signal at start-up, so the vanished worker was a native program that kept the default (C, like dd), or Python that reset the disposition or started a native child
You want the error in your logs, not a silent deathPython already ignores the signal; in C, ignore or handle it before the writeThen the crossing write raises EFBIG, and your handler, retry and metric all run
The same write works in staging and fails in productionCompare Max file size in both processes’ /proc/<pid>/limitsThe limit belongs to the process; the filesystem and the free space do not move
A buffered writer reported a full write and lost the tailFlush before you trust the length, and treat a flush error as the write’s errorThe buffer accepted 5,000 bytes and stored none; the flush stored what fit and raised
A copy stopped part-way and left a truncated fileCheck the return of sendfile, copy_file_range and shutil.copyfileThe first two return the bytes they moved; the third raises after a partial file is on disk
truncate or fallocate refused a size the disk could holdExpect EFBIG from both: they are checked against the same ceilingThe limit is applied to the call’s end offset, not to the free space
A memory-mapped writer was never refusedDo not rely on the limit to stop mmap writesA write through a mapping does not take the write path, so nothing checks it
The file genuinely has to be larger than the ceilingRaise the soft limit up to the hard limit, or write another fileThe hard limit is the boundary; a rollover to a second file needs no privilege
You cannot tell who set 4,096 bytesWalk the process tree and read each ancestor’s row, then check the service or container settingA limit is inherited; the number usually belongs to the shell, unit or runtime above the process
Table 1: ten changes, each matched to an observation, with the mechanism that makes it work. The fifth row’s 5,000 bytes and the first row’s round number are measurements from Section 5, not illustrations.

1. One number, three questions

OSError: [Errno 27] File too large arrives with a question already attached: is the disk full, is a quota exhausted, or is this process not allowed to grow a file that far? The three answers have different owners and different fixes, and the errno tells them apart before you look at anything else.

EFBIG is the third answer. It is produced by the process’s own limit, RLIMIT_FSIZE, and it fires on a host with terabytes free: the host measured here has a soft limit of 536,870,912 bytes, which is generous, and every experiment below lowered it to 4,096 bytes in a child process to make the boundary visible. The disk never entered the picture.

NumberName on LinuxMessageWhat it actually means
27EFBIGFile too largeThis process tried to grow one file past its own ceiling; the disk may be empty
28ENOSPCNo space left on deviceThe filesystem has no free block or no free inode left for anyone
122EDQUOTDisk quota exceededAn administrator’s quota for this user or group is used up
75EOVERFLOWValue too large for defined data typedocumented: a 32-bit build that opens a file already past 2 GiB without O_LARGEFILE gets this from open(2), and the write that crosses the same ceiling gets 27
22EINVALInvalid argumentA size or flag the call cannot represent, refused before anything is written
Table 2: five numbers that reach the same log line. Names and messages are the interpreter’s own (errno, os.strerror); the meaning column is what the calls behind them do, measured in Sections 3 to 6, and the one row that was not run here says documented and links its page.

Two of those neighbours are a different investigation, and this site already has the runbook for the first: a filesystem with no block or inode left is errno 28, and a name too long for a directory is errno 36 – a limit counted in bytes too, in a different place. Both are worth ruling out before touching a file-size limit.

The distinction matters most when the ceiling is small. A 4,096-byte limit looks like a bug in a disk monitor: df shows plenty of free space, the write fails, and both observations are true.

macOS gives the same condition the same name and number – EFBIG, 27 – and Windows calls it ERROR_FILE_TOO_LARGE, 223. Both are documented rather than measured here: the XNU errno header and the Windows system error codes. The numbers are the same idea in three places, which is why a runbook written from a macOS or Windows incident transfers.

2. What was measured here, and what was not

Everything numbered in this page comes from a probe whose record is printed in Appendix B: a child process, a lowered limit, and a JSON line written by that child before it exited. Where a child was expected to die, the record is the wait status and the signal, because a dead process cannot write a file.

ItemThis hostWhy it is stated
Kernel6.12.118-guest-1.2the call path and the file limit are kernel-side
InterpreterPython 3.12.16the exception type and buffering are the interpreter’s
Machinex86_64, 2 vCPUone host, not a fleet
Useruid 1000no root, so no mount, quota or cgroup experiment
Filesystems/tmp (tmpfs) and /workspace (virtiofs)both gave the same boundary; the limit is not a filesystem property
Process limitsoft 536,870,912 bytes, hard 536,870,912 bytesthe ceiling the experiments were measured against
Table 3: the host, in six facts. The child processes that were given a 4,096-byte limit changed nothing else about it.

Four things were deliberately not measured. A cgroup v2 memory limit and the service manager’s LimitFSIZE need root and a unit file; the container runtime’s --ulimit fsize needs a runtime that is not installed here; the 32-bit large-file path needs a 32-bit interpreter, which this image does not carry; and a filesystem whose own maximum file size is smaller than the limit needs a filesystem this host does not have. They are named in Sections 3 and 9 as documented behaviour and are not counted as results.

Figures taken from documentation rather than from this host say so where they appear: the macOS and Windows numbers in Section 1, the EOVERFLOW row of Table 2, the core-dump action of SIGXFSZ (this host keeps no core, because the core limit is 0 bytes), the filesystem ceiling and MAX_NON_LFS branch in Section 3, the CPython start-up quoted in Section 4, and the POSIX block size behind ulimit -f. If a number is in neither a results file nor such a sentence, it is not on this page.

3. The limit, and the byte after it

Start with the smallest experiment that shows the whole behaviour. A child process sets its soft limit to RLIMIT_FSIZE = 4,096, creates a file, writes exactly as many bytes as the limit allows, and then writes one more byte. The same child is run five times at each of five limits, so a boundary is five attempts rather than one, and every attempt in an arm agreed with the others.

Limit (bytes)Write of exactly that many bytesFile after itNext byte: what happened
0wrote nothing0 bytesSIGXFSZ before a byte was stored
1returned 11 byteSIGXFSZ, file unchanged
1,024returned 1,0241,024 bytesSIGXFSZ, file unchanged
4,096returned 4,0964,096 bytesSIGXFSZ, file unchanged
65,536returned 65,53665,536 bytesSIGXFSZ, file unchanged
Table 4: the exact boundary at five limits, five runs each, with the kernel’s default action for SIGXFSZ in force. The write of exactly the limit succeeded every time; the byte after it never did.

The five rows say something narrower than they appear to. They do not show that a large write fails; the next table shows the opposite. They show that the boundary is checked against the file’s offset when the write starts: a write whose first byte is at the limit is refused before it stores anything, and a write that starts below it is simply shortened. At limit 0 even the first byte is past the ceiling, which is why that row dies before it can report a count.

Limit (bytes)One call asking forReturnedStored in the file
04,096 bytesnothing: SIGXFSZ0 bytes
14,097 bytes11 byte
1,0245,120 bytes1,0241,024 bytes
4,0968,192 bytes4,0964,096 bytes
65,53669,632 bytes65,53665,536 bytes
Table 5: one oversized call at each limit. The call does not fail: it stores exactly as many bytes as the limit allows and returns that count, and the caller is expected to notice the short return.

The asymmetry between Table 4 and Table 5 is not an accident of the interpreter. It is the function below – generic_write_check_limits, in the kernel’s fs/read_write.c, copied from the source at the URL in Section 9 – which every buffered write to a regular file passes through, and its two branches decide what a clipped write returns and when the signal is sent.

int generic_write_check_limits(struct file *file, loff_t pos, loff_t *count)
{
	struct inode *inode = file->f_mapping->host;
	loff_t max_size = inode->i_sb->s_maxbytes;
	loff_t limit = rlimit(RLIMIT_FSIZE);

	if (limit != RLIM_INFINITY) {
		if (pos >= limit) {
			send_sig(SIGXFSZ, current, 0);
			return -EFBIG;
		}
		*count = min(*count, limit - pos);
	}

	if (!(file->f_flags & O_LARGEFILE))
		max_size = MAX_NON_LFS;

	if (unlikely(pos >= max_size))
		return -EFBIG;

	*count = min(*count, max_size - pos);

	return 0;
}

The first branch is the one Table 4 shows: a write that starts at or past the limit is signalled and refused. The second branch is the one Table 5 shows: a write that starts below the limit has its count reduced to the room that is left, so 1,096 bytes of a 2,000-byte write at offset 3,000 is not a partial I/O in the networking sense – it is the kernel doing exactly what it was told. The two branches are also why the errno is secondary: on the clipping path there is no errno at all, only a smaller number than the caller asked for.

A short count is the same shape of failure as a reader that leaves early, which is what errno 32 describes: the call reports what it managed, and the rest is the caller’s problem. The difference is that nothing here is broken – the limit is doing its job.

The function holds two more ceilings that return the same errno with free space to spare. The first is the filesystem’s own maximum file size: max_size starts at s_maxbytes from the superblock, and a write past it is refused the same way. The second is MAX_NON_LFS, applied when a file was opened without O_LARGEFILE: a 32-bit process without that flag cannot grow a file past 2 GiB, and open(2) refuses to open one that is already larger, which is the EOVERFLOW row of Table 2. This image is 64-bit, where the kernel adds the flag to every open, and its filesystems allow files far beyond any this host could hold, so neither branch could fire in the runs below; both are documented rather than measured here.

4. The signal decides what you see

The call path sends SIGXFSZ and returns EFBIG at the same moment, and which of the two reaches your code depends on the signal’s disposition. Four children were run with the same 1,024-byte limit and the same two writes, differing only in how SIGXFSZ is set before the first byte.

Disposition in the childSecond writeWhat the process didShell status
nothing changed (the interpreter’s own SIG_IGN)raised errno 27survived, printed its JSON line0
SIG_DFL, the kernel’s defaultnever returned: SIGXFSZkilled by SIGXFSZ, nothing on stderr153
SIG_IGNraised errno 27survived, printed its JSON line0
a Python handlerraised errno 27handler ran, then the write raised0
Table 6: four dispositions, one limit of 1,024 bytes, five runs each. The first row changed nothing and still survived, because CPython set SIGXFSZ (25) to SIG_IGN before the program’s first line ran.

The default action is termination, and it is not a Python exception with a bad message. The process is gone before the call returns; the only evidence is the wait status. A shell reports it as 153, which is 128 plus the signal number, and a supervisor reports the same thing as a signal rather than an exit code. There is no traceback to grep for, because no frame ever resumed.

The man page says the action is termination with a core dump, and this host disables core files: the core limit is 0 bytes, so the kill leaves no core to inspect either. That is a property of this host, not of the signal, and it is the reason an incident here looks like a worker that vanished.

Which row you get is not a matter of taste in Python, and it is not a matter of inheritance either. While the main interpreter starts, _PySignal_Init() calls signal_install_handlers(), which sets SIGXFSZ and SIGPIPE to SIG_IGN. That line has been on the start-up path far longer than its current file: Python 2.7.18 sets it in Python/pythonrun.c; Python 3.5.10, 3.6.15 and 3.7.17 set it in Python/pylifecycle.c through initsigs(); Python 3.8.0 and 3.9.0 use the same file through init_signals(); and Python 3.10.0 through 3.12.16 use Modules/signalmodule.c. Every release checked here begins with the signal ignored whatever the launcher passed, and the move in Python 3.10 changed the file, not the behaviour. _Py_RestoreSignals() is the counterweight, and it does not run at shutdown: subprocess calls it in the child before exec when restore_signals is true, which is why the /bin/cat rows of Table 7 differ. The sources for every version are linked in Section 9.

Two explanations fit the surviving child – a SIG_IGN inherited through exec, and the interpreter’s own start-up – and four processes separate them. Each one read its mask from /proc/self/status, five runs each, and every run in an arm agreed.

ProcessSIGXFSZ when it starts writingWho set that
/bin/cat, started by Python with restore_signals=True (the default)defaultsubprocess, which restored SIG_DFL before exec
/bin/cat, started with restore_signals=Falseignoredthe parent: SIG_IGN survives exec
python3, whose launcher had set SIG_DFLignoredCPython, while the interpreter starts
/bin/cat, whose launcher had set SIG_DFLdefaultnobody
Table 7: four processes, one question, five runs each. Rows two and three are the two answers that get confused: an inherited SIG_IGN and an interpreter that sets its own. Rows one and four are the control – a C program begins at the kernel’s default either way, so nothing outside a process sets this.

The prediction holds on a writer that is not Python. dd asked for 8,192 bytes under a 4,096-byte limit died from SIGXFSZ five times out of five: status 153, nothing on stderr, a 4,096-byte file left behind. The same crossing write in Python raised errno 27 five times out of five, and with one line added at the top – signal.signal(signal.SIGXFSZ, signal.SIG_DFL) – it died with status 153 as well.

The practical consequence is the opposite of the usual advice. In Python there is nothing to install: the crossing write already raises, and the work is to let the exception be seen – do not reset the disposition, and do not catch EFBIG and retry the same bytes. In C, one call at start-up does what CPython does: ignore the signal so write returns EFBIG, then treat the errno as the error it is.

5. What actually lands on disk

Knowing that a write can be short is not the same as knowing what a program leaves behind. Seven writers were pointed at a 4,096-byte limit, each in its own child, and each was asked what it returned, what the limit cost it, and what the file held afterwards.

WriterWhat it asked forWhat it returnedFile afterwards
os.write, one call5,000 bytes4,0964,096 bytes; the next write raised 27
os.writev, two buffers3,000 + 3,000 bytes4,0964,096 bytes
os.pwrite, at offset 3,0002,000 bytes1,0964,096 bytes
open(..., 'wb', buffering=8192)5,000 bytes5,000, then the flush raised 274,096 bytes; the close raised 27 as well
open(..., 'w'), text mode5,000 characters5,000, then the flush raised 274,096 bytes
overwrite inside a larger file1 byte at 0, then 200 bytes at 4,0001 byte, then 96 bytesstill 8,192 bytes; extending it raised 27
append to a file already at the limit1 byteraised 274,096 bytes, unchanged
Table 8: seven writers, one limit, five runs each. Rows four and five report two errors because the buffer and the file object each flush the same bytes.

The buffered rows are the ones that lose data quietly in production. The write call succeeded – it returned the full 5,000 – because the bytes went into a buffer. The flush stored what fit and raised, and the close raised a second time for the same reason. A program that checks only the write’s return value logs success and ships a file that ends at a round number, which is exactly the first row of Table 1.

The sixth row shows that the limit is not a limit on the file’s length, but on where a write may end. The file was 8,192 bytes and the ceiling was 4,096: a one-byte overwrite at offset 0 was allowed, a 200-byte write at offset 4,000 was cut to 96 bytes, and a write that would extend the file was refused. Nothing truncated the 8,192 bytes that were already there – the limit gates growth, it does not shrink a file that grew before it applied.

6. Which calls answer the limit

Fourteen calls were run against the same 4,096-byte limit, each in a child, so that a call which kills its process is still a row rather than a gap. The column that matters is the last one: what a reader of the code would find on disk after the call returned.

CallAt a 4,096-byte limitWhat it left behind
os.write(fd, 5,000 bytes)returned 4,0964,096 bytes
os.pwrite(fd, 5,000 bytes, 0)returned 4,0964,096 bytes
os.writev(fd, two buffers)returned 4,0964,096 bytes
os.truncate(path, 8192)raised 27unchanged at 1 byte
os.ftruncate(fd, 8192)raised 27unchanged at 1 byte
os.posix_fallocate(fd, 0, 8192)raised 27unchanged at 0 bytes
os.sendfile(out, in, 0, 8192)returned 4,0964,096 bytes
os.copy_file_range(in, out, 8192)returned 4,0964,096 bytes
mmap of an 8,192-byte file, byte at offset 5,000no error (no fault)still 8,192 bytes
pathlib.Path.write_bytes with an 8,000-byte objectraised 27partial file of 4,096 bytes
shutil.copyfile of an 8,192-byte sourceraised 27partial file of 4,096 bytes
os.lseek(fd, 999999)returned 999,999an offset, no file growth
os.write to /dev/nullreturned 5,000not a regular file, so not checked
os.write to a pipereturned 5,000not a regular file, so not checked
Table 9: fourteen calls, one limit, five runs each. Where a row returns a count it is the number of bytes the call handled; lseek returns an offset instead, and stores nothing.

Three groups of rows are worth pausing on. truncate and fallocate are refused outright, because their end offset is the number the limit checks; there is no bytes-that-fit version of them. sendfile and copy_file_range clip like write but return a count a caller is even less likely to check, and shutil.copyfile leaves the truncated target behind when it raises.

The mmap row is the one that reads like a bug and is not. A write through a mapping does not call write; it faults a page in and marks it dirty, so it never reaches the function that holds the limit. It also cannot extend the file, so the only checks that could apply are the mapping’s own bounds. A program that preallocates a large file and writes through a mapping can therefore put data far past a limit that would refuse every write call it makes.

/dev/null and a pipe show the other edge: the limit is a property of regular files. Writing 5,000 bytes to either one succeeded at a limit that refused the same write to a file, which is why a service that only logs to stdout can run for months under a limit its file writes would have hit on the first day.

The offset itself is not checked by lseek: seeking past the limit succeeds and leaves the file empty, and the refusal comes at the next write. The next table puts the two together, because the offset is the variable that decides which of the kernel’s two branches runs.

Where the write startsBytes asked forReturnedFile afterwards
offset 2,0001001002,100 bytes
offset 4,095114,096 bytes
offset 4,095214,096 bytes
offset 4,096, exactly the limit1raised 270 bytes
offset 10,000, past the limit1raised 270 bytes
offset 0, then fsync5,0004,0964,096 bytes
Table 10: the same limit, six starting offsets. A write at 4,095 asking for two bytes gets one; a write at 4,096 asking for one gets nothing and a signal.

The last row is the one to remember when a clipped write is followed by fsync: the sync succeeds, because there is nothing wrong with the bytes that were stored. Durability says nothing about completeness, and neither does a successful close on a raw descriptor.

7. A module that never crosses

Everything above reduces to three jobs: read the ceiling, write only what fits, and say what happened when the rest does not. The module in Appendix A is those three jobs, 199 lines in 4 files with 36 tests. It is printed there once, in full, so this section can stay short.

budget() returns both ends of the limit, and ceiling() turns the soft limit into the number a caller compares against – None when nothing caps the file, which is a different answer from zero. describe() turns an errno into one sentence that names the file, the limit and the thing that is not the problem, because the first instinct after EFBIG is to look at free space. room() answers how much the file may still grow by.

The heart is write_up_to. It asks the kernel for a count whose end offset is inside the limit, so the kernel never has a reason to signal, and it returns the bytes that were stored:

import os
from .limits import ceiling


def write_up_to(fd: int, data: bytes, limit: int | None = None) -> int:
    """Write the part of ``data`` that fits below the limit, and never cross it.

    The count it asks the kernel for ends at the limit at worst, so the write is not refused:
    no EFBIG and no SIGXFSZ, unless another process grows the file before ``append`` writes.
    """
    cap = ceiling(limit)
    if cap is None:
        return os.write(fd, data)
    allowed = min(len(data), max(0, cap - os.lseek(fd, 0, os.SEEK_END)))
    if allowed <= 0:
        return 0
    return os.write(fd, data[:allowed])

write_all wraps it in the contract a log writer wants – every byte, or a LimitReached that carries what was written and what the limit was – and append is the same function opened with O_APPEND, where the offset a write lands at is the file’s end rather than the descriptor’s position. guard() and restore() cover the one case the interpreter does not: a program that put the default back.

The module was then run under the same limit as everything else. Table 11 is its own answers, taken from children at 4,096 bytes.

What was calledWhat it did
os.write past the limit with SIG_DFL set, no guardprocess ended by SIGXFSZ
os.write past the limit, after guard()raised 27, file 4,096 bytes
write_up_to(fd, 5,000 bytes)returned 4,096, no signal
write_all(fd, 5,000 bytes)raised after 4,096 bytes, limit 4,096
append(path, 1 byte) at the limitraised after 0 bytes, file still 4,096
budget()soft 4,096, hard 4,096
describe(OSError(27, ...), 4,096)EFBIG on /var/log/app.log: this process may grow one file to 4,096 bytes, the row Max file size in /proc/<pid>/limits holds it, and the write ended past it; free disk space is not the question.
line()Max file size 4096 4096 bytes
Table 11: the module under the same limit, five runs per row. The first two rows differ only in the signal’s disposition, and they are the whole argument of Section 4.

When the file genuinely has to be larger than the ceiling, the module’s answer is another file, not a larger buffer: a rollover names a second file, needs no privilege, and keeps the first one complete. Raising the soft limit up to the hard limit is the other option, and Section 9 is where that belongs.

Reading the limit is not free, and it is worth knowing how much it costs before putting it in a loop. Each arm below timed 200 calls per run, five runs per arm, on this host.

CallMedian (range of five runs)What the number is
resource.getrlimit88.84 µs (80.38–390.35)the syscall itself
budget()94.65 µs (89.63–156.64)one dict per call
ceiling()87.56 µs (86.90–91.91)the number a write uses
line(), reading /proc3166.73 µs (2930.04–3555.82)a file read, not a syscall
room(fd, 4,096)100.00 µs (99.16–151.62)one seek plus the ceiling
os.lseek(fd, 0, SEEK_END)45.21 µs (45.05–47.23)the seek alone
Table 12: cost per call, median of five runs of 200 calls each, measured on one 2 vCPU VM with the filesystems of Table 3. The microseconds belong to that host and move with the machine; the ratio does not – a /proc read costs about 36 times a limit lookup here, and the gap stays wide because one is a file read and the other a syscall.

That difference decides the shape of the code: read the ceiling when a file is opened, keep the number next to the descriptor, and compare against it on each write. Reading /proc per write would cost more than the write it protects. Treat the table as a portable ordering, not as timings to quote in another budget: a laptop, a container and a mount with a slow metadata path each move the numbers.

The example in Appendix B does the smallest useful version of all this: two children with the same limit and different dispositions, then the module. Its output is short enough to read as a table of its own.

condition                              answer
limit 4,096, SIGXFSZ default           signal 25
limit 4,096, SIGXFSZ ignored           EFBIG after 4,096 bytes
fslimit.write_up_to                    4,096 bytes written, no signal
fslimit.budget (this process)          {soft: 536870912, hard: 536870912}
fslimit.disposition (this process)     ignored

8. Diagnosis in six commands

The order below is the order that costs least. The first two commands answer whether the limit exists and what it is; the next two answer whether anyone will see an error at all; the last two find the process that handed the number down.

CommandWhat it tells youWhat this host answered
grep 'Max file size' /proc/<pid>/limitsthe soft and hard limit, in bytes, in the kernel’s own wordsMax file size 536870912 536870912 bytes
prlimit --pid <pid> --fsizethe same two numbers, and lets you set theminstalled here; not used on a live service in this run
ulimit -fwhat a shell will hand to the next command4,096 bytes in sh, 8,192 in bash, both from ulimit -f 8
grep SigIgn /proc/<pid>/statuswhether the next crossing write raises or ends the processbit 25 set, because CPython set it
exit status, from a log or a supervisor153 means a signal death, not an exit codeseen in every default-disposition child in Table 6
PPid chain, then the unit or runtime above itwho to change, rather than what to change in this processthe limit in Table 3 is inherited from the runner
Table 13: six commands, what each answers, and the answer on this host. The third row is the trap: ulimit -f counts blocks, and the block it counts depends on which shell parsed the command.

The third row deserves its own sentence, because it is the one number in this page that two shells disagree about. ulimit -f 8 produced a 4,096-byte limit under sh and an 8,192-byte limit under bash on the same host: one counted 512-byte blocks and the other counted 1,024-byte blocks. The POSIX specification says 512, which matches the first; a shell that uses 1,024 will set twice the intended limit without saying so. Reading the limit back from the kernel – /proc/self/limits, or resource.getrlimit – is the only way to be sure which one you got.

A refusal that comes before any work starts is easier to diagnose than one that arrives mid-write, and this site has the same lesson for a lookup that loops (the ELOOP runbook) and for a connection nobody accepted (the ECONNREFUSED runbook). In all three, the status is more informative than the message.

After the six commands, the change itself is usually one of two kinds: raise the ceiling for a process that must write a larger file, or stop assuming a write wrote everything. The first is an operational change with a hard boundary you cannot cross without privilege; the second is a code change that counts what came back and handles the rest. In Python the signal is already ignored, so the second kind has an exception to catch; in C it is worth one call to give it one.

9. Where the limit comes from, and how to change it

A limit is inherited, so the number a process runs under was almost always set somewhere else. Each row below names a place it can be set, what that place sets, and whether this host could exercise it.

WhereHow it is setWhat changesMeasured here
the shellulimit -f 8a soft and hard limit of 4,096 or 8,192 bytes, depending on the shellyes
a running processprlimit --pid N --fsize=BYTESthe soft limit, and the hard one with privilegeno: nothing long-running to change
the service managerLimitFSIZE=BYTES in a unitboth ends, for every process the unit startsno: no unit here
the container runtime--ulimit fsize=BYTESboth ends, inherited by the container’s first processno: no runtime here
a parent processany of the above, before it forksboth ends, copied at fork and carried across execyes, by construction
the process itselfresource.setrlimit(RLIMIT_FSIZE, ...)the soft limit, up to the hard limit; raising the hard one needs privilegeyes, in every child
Table 14: six places a file-size limit is set. The first row is the one that produces surprises, because the unit it counts in is not the unit the kernel reports.

The last two rows are the ones a program controls. It can lower its own soft limit, and it can raise it back up to the hard limit, and it can do nothing about the hard limit without privilege. That asymmetry is why a service that hits the ceiling in production usually needs an operator even though the fix looks like one line.

The pages these statements come from, all of them read for this article: errno(3), getrlimit(2) for the limit and the signal, write(2), open(2) for the file that is too large to open, signal(7) for the default action, truncate(2), posix_fallocate(3), copy_file_range(2), proc_pid_limits(5), the kernel function that applies the limit, the CPython start-up that ignores the signal, the same line before the move in Python 2.7.18, Python 3.7.17 and Python 3.8.0, and the POSIX ulimit utility, with the two platform pages quoted in Section 1.

The rest is a design choice the measurements make easy. If a file can approach the ceiling, write another file when the first is full, and keep the first one complete. If the ceiling is a mistake in configuration, read the hard limit first and raise the soft one only to that. Either way, check the count each write returns and make the signal visible, because a process that vanishes has told you nothing and a short count has told you everything.

Questions This Page Answers

Is errno 27 the same as a full disk?

No. A full filesystem answers 28 (No space left on device) when the last block or inode is taken. EFBIG answers a limit owned by your process, and the disk can be empty when it fires.

Why did my process disappear with no traceback?

The kernel sent SIGXFSZ (25) and its default action is to terminate. A shell reports that as status 153; a supervisor reports a signal. Nothing is printed because no frame ever resumed. Python does not take this route by default – the interpreter ignores the signal before your code runs – so the writer that vanished was a native program that kept the default action (C, like dd), or Python that reset SIGXFSZ to SIG_DFL or started such a program of its own.

How do I get an exception instead of a disappearance?

In Python it is already there: CPython sets SIGXFSZ to SIG_IGN at start-up, so the crossing write raises OSError with EFBIG. In C the same write returns EFBIG if the signal is ignored, so ignore or handle it once before the first write.

Why did write() return a smaller number than I passed?

The write began below the limit and the kernel cut its count to the room that was left. That is a short write, not an error: the caller is expected to check the count and continue at the new offset.

Why did the write report success and the file end short?

Because it was a buffered write. The buffer accepted every byte and stored none; the flush stored what fit and raised. A program that checks only the write’s return value sees success.

Does raising the limit fix it?

Only up to the hard limit, which the process cannot raise itself. A soft limit raised to the hard one fixes a configuration mistake; a file that must be larger than the hard limit needs another file or an operator.

Why does a file already hold more bytes than the limit?

The limit gates growth, not length. A file that grew before the limit applied keeps its bytes; writes wholly below the ceiling are allowed, and writes that would extend it are refused.

Do truncate and fallocate behave like write?

No. They are refused outright with EFBIG when their end offset is past the limit; there is no bytes-that-fit version, and the file is left as it was.

Does a memory-mapped write hit the limit?

No. A write through a mapping does not take the write path, so the check never runs. It also cannot extend the file, which is why the two facts are compatible.

Does the limit apply to a pipe, to /dev/null or to stdout?

Only if the descriptor is a regular file. The same 5,000-byte write that a 4,096-byte limit refused for a file was accepted by a pipe and by /dev/null; a shell redirect of stdout into a file is still a file, so that one is checked.

Who set 4,096 bytes when I never set it?

Whatever started the process. A limit is inherited across fork and exec, so the shell, the unit or the container runtime above the process is the place to look, and PPid is the first step. The signal is a separate question: in Python the interpreter sets its own disposition for SIGXFSZ.

Is the limit per thread or per process?

Per process: every thread shares the one limit, so a write in a worker thread meets the same ceiling as the main thread and can end the whole process with the same signal.

Appendix A: the module and its tests, in full

Four files and three test files, 199 lines of module and 253 lines of tests. They are printed as they ran: the 36 passing tests in Table 11’s section are this text.

the package’s exports fslimit/__init__.py
"""fslimit: the file-size limit behind errno 27, read, respected and explained.

    >>> from fslimit import budget, ceiling, write_all, LimitReached
    >>> budget()["soft"]                       # None when nothing limits a file
    >>> write_all(fd, b"x" * 5000, limit=4096)  # writes 4,096, then raises LimitReached
"""
from .diagnose import disposition, guard, parent_chain, restore
from .limits import budget, ceiling, describe, line
from .write import LimitReached, append, room, write_all, write_up_to

__all__ = ["LimitReached", "append", "budget", "ceiling", "describe", "disposition", "guard",
           "line", "parent_chain", "restore", "room", "write_all", "write_up_to"]
reading the limit, and describing EFBIG fslimit/limits.py
"""Read a process's file-size limit, and say what EFBIG meant when it fired."""
from __future__ import annotations

import errno
import pathlib
import resource

INFINITY = resource.RLIM_INFINITY
LINE = "Max file size"
PROC = pathlib.Path("/proc/self/limits")


def budget() -> dict:
    """The soft and hard file-size limit of this process, in bytes, ``None`` for no limit.

    These are the numbers a write here is measured against; another process's limit is only in
    its own ``/proc`` row, which :func:`line` prints.
    """
    soft, hard = resource.getrlimit(resource.RLIMIT_FSIZE)
    return {"soft": None if soft == INFINITY else int(soft),
            "hard": None if hard == INFINITY else int(hard)}


def ceiling(soft: int | None = None) -> int | None:
    """The number of bytes one file may reach, or ``None`` when nothing caps it.

    ``soft=None`` reads this process's own soft limit, which is the one a write here meets.
    """
    if soft is None:
        soft = resource.getrlimit(resource.RLIMIT_FSIZE)[0]
    return None if soft == INFINITY else int(soft)


def line(pid: int | str = "self") -> str:
    """The kernel's own row for this limit, with its whitespace normalised."""
    path = PROC if pid == "self" else pathlib.Path(f"/proc/{pid}/limits")
    for row in path.read_text().splitlines():
        if row.startswith(LINE):
            return " ".join(row.split())
    return ""


def describe(exc: OSError, soft: int | None = None) -> str:
    """One sentence for an EFBIG that names the limit, the file, and the wrong suspect."""
    if getattr(exc, "errno", None) != errno.EFBIG:
        raise ValueError(f"not a file-size refusal: errno {getattr(exc, 'errno', None)}")
    cap = ceiling(soft)
    if cap is None:
        allowance = "this process has no limit on a file's size"
    else:
        allowance = f"this process may grow one file to {cap:,} bytes"
    name = getattr(exc, "filename", None) or "the file"
    return (f"EFBIG on {name}: {allowance}, the row Max file size in /proc/<pid>/limits holds "
            f"it, and the write ended past it; free disk space is not the question.")
writing what fits, and the exception for the rest fslimit/write.py
"""Write what fits, and report the rest instead of dying on SIGXFSZ."""
from __future__ import annotations

import errno
import os

from .limits import ceiling

O_BYTES = os.O_WRONLY | os.O_CREAT


class LimitReached(OSError):
    """Raised after the bytes that fit were written; ``written`` says how many."""

    def __init__(self, limit: int | None, written: int, path: str | None = None):
        super().__init__(errno.EFBIG, "File too large", path)
        self.limit = limit
        self.written = written

    def __str__(self) -> str:
        room = "no limit" if self.limit is None else f"limit {self.limit:,}"
        return f"wrote {self.written:,} bytes, then the file-size limit ({room}) stopped it"


def room(fd: int, limit: int | None = None) -> int | None:
    """How many more bytes this file may grow by, or ``None`` if nothing caps it."""
    cap = ceiling(limit)
    if cap is None:
        return None
    return max(0, cap - os.lseek(fd, 0, os.SEEK_END))


def write_up_to(fd: int, data: bytes, limit: int | None = None) -> int:
    """Write the part of ``data`` that fits below the limit, and never cross it.

    The count it asks the kernel for ends at the limit at worst, so the write is not refused:
    no EFBIG and no SIGXFSZ, unless another process grows the file before ``append`` writes.
    """
    cap = ceiling(limit)
    if cap is None:
        return os.write(fd, data)
    allowed = min(len(data), max(0, cap - os.lseek(fd, 0, os.SEEK_END)))
    if allowed <= 0:
        return 0
    return os.write(fd, data[:allowed])


def write_all(fd: int, data: bytes, limit: int | None = None) -> int:
    """Write every byte, or raise :class:`LimitReached` after writing the ones that fit."""
    written = write_up_to(fd, data, limit)
    if written != len(data):
        raise LimitReached(ceiling(limit), written)
    return written


def append(path: str, data: bytes, limit: int | None = None) -> int:
    """Append to a file, writing only the part that fits; returns the bytes written."""
    fd = os.open(path, O_BYTES | os.O_APPEND, 0o644)
    try:
        return write_all(fd, data, limit)
    finally:
        os.close(fd)
the signal, the disposition, and the process tree fslimit/diagnose.py
"""Turn the signal into an exception, and find who set the limit.

CPython sets SIGXFSZ to SIG_IGN while it starts, so in a live interpreter the write already
raises. The guard here is for a process that put the default back.
"""
from __future__ import annotations

import os
import pathlib
import signal

LINE = "Max file size"


def guard() -> object:
    """Ignore SIGXFSZ, so an over-limit write raises EFBIG instead of killing the process.

    A running CPython has already done this while it started; the call is what a process that
    set SIG_DFL itself needs, and it costs one call. Returns the disposition that was in force,
    so the caller can hand it back to :func:`restore`.
    """
    previous = signal.getsignal(signal.SIGXFSZ)
    signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
    return previous


def restore(previous: object) -> None:
    """Put back the disposition :func:`guard` replaced."""
    signal.signal(signal.SIGXFSZ, previous)


def disposition() -> str:
    """What the kernel will do to this process on the next crossing write.

    ``ignored`` means the write raises EFBIG; ``default`` means the process dies. The mask in
    /proc/self/status is the live answer, and in Python it is ``ignored`` whatever the launcher
    passed, because CPython sets SIGXFSZ to SIG_IGN while it starts. The ``default`` case is a
    program that set it back, or one that is not Python.
    """
    for row in pathlib.Path("/proc/self/status").read_text().splitlines():
        if row.startswith("SigIgn:"):
            mask = int(row.split()[1], 16)
            return "ignored" if mask & (1 << (signal.SIGXFSZ - 1)) else "default"
    return "unknown"


def parent_chain(pid: int | None = None, depth: int = 4) -> list[dict]:
    """Walk up the process tree, printing each ancestor's file-size row.

    A limit is inherited, so the process that set it is often the parent or the service manager
    above it; this is the cheap way to see where a surprising number came from.
    """
    chain: list[dict] = []
    current = pid or os.getpid()
    for _ in range(depth):
        try:
            status = pathlib.Path(f"/proc/{current}/status").read_text()
            limits = pathlib.Path(f"/proc/{current}/limits").read_text()
            name = next(row.split("\t")[-1] for row in status.splitlines()
                        if row.startswith("Name:"))
            parent = int(next(row.split("\t")[-1] for row in status.splitlines()
                              if row.startswith("PPid:")))
            row = next((r for r in limits.splitlines() if r.startswith(LINE)), "")
        except (OSError, StopIteration):
            break
        chain.append({"pid": current, "name": name, "ppid": parent,
                      "line": " ".join(row.split())})
        if parent in (0, current):
            break
        current = parent
    return chain
tests for reading and describing fslimit/tests/test_limits.py
"""Reading the limit and turning EFBIG into a sentence."""
from __future__ import annotations

import errno
import resource

import pytest

from fslimit import budget, ceiling, describe, line


def test_budget_names_both_ends():
    got = budget()
    assert set(got) == {"soft", "hard"}
    assert isinstance(got["soft"], int) and isinstance(got["hard"], int)


def test_budget_reports_the_soft_limit_this_process_runs_under():
    assert budget()["soft"] == resource.getrlimit(resource.RLIMIT_FSIZE)[0]


def test_ceiling_of_a_number_is_that_number():
    assert ceiling(4096) == 4096


def test_zero_is_a_ceiling_not_an_absence():
    assert ceiling(0) == 0


def test_infinity_is_no_ceiling():
    assert ceiling(resource.RLIM_INFINITY) is None


def test_line_is_the_kernels_own_row():
    row = line()
    assert row.startswith("Max file size")
    assert row.endswith("bytes")


def test_describe_prints_the_limit_with_separators():
    sentence = describe(OSError(errno.EFBIG, "File too large", "/tmp/x"), 4096)
    assert "4,096 bytes" in sentence
    assert "free disk space is not the question" in sentence


def test_describe_names_the_file_it_refused():
    assert "/var/log/app.log" in describe(
        OSError(errno.EFBIG, "File too large", "/var/log/app.log"), 1024)


def test_describe_says_so_when_nothing_limits_the_file():
    assert "no limit" in describe(OSError(errno.EFBIG, "File too large", "f"),
                                   resource.RLIM_INFINITY)


def test_describe_refuses_a_different_errno():
    with pytest.raises(ValueError):
        describe(OSError(errno.ENOSPC, "No space left on device", "/tmp/x"), 4096)


def test_describe_is_not_fooled_by_a_missing_errno():
    with pytest.raises(ValueError):
        describe(OSError("no errno here"), 4096)
tests for the bounded writers fslimit/tests/test_write.py
"""Writing under a limit: the bytes that fit, the exception for the rest."""
from __future__ import annotations

import errno
import os
import resource
import signal

import pytest

from fslimit import LimitReached, append, room, write_all, write_up_to

CAP = 4096


@pytest.fixture(autouse=True)
def small_limit():
    """Lower the soft limit for one test, and put it back whatever the test does."""
    original = resource.getrlimit(resource.RLIMIT_FSIZE)
    signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
    resource.setrlimit(resource.RLIMIT_FSIZE, (CAP, original[1]))
    try:
        yield
    finally:
        resource.setrlimit(resource.RLIMIT_FSIZE, original)


@pytest.fixture()
def handle(tmp_path):
    path = tmp_path / "report.bin"
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
    try:
        yield fd, path
    finally:
        os.close(fd)


def test_a_short_write_is_written_whole(handle):
    fd, path = handle
    assert write_up_to(fd, b"a" * 100) == 100
    assert path.stat().st_size == 100


def test_a_long_write_stops_at_the_limit(handle):
    fd, path = handle
    assert write_up_to(fd, b"a" * 5000) == CAP
    assert path.stat().st_size == CAP


def test_a_write_at_the_limit_writes_nothing(handle):
    fd, path = handle
    write_up_to(fd, b"a" * 5000)
    assert write_up_to(fd, b"b") == 0
    assert path.stat().st_size == CAP


def test_write_all_returns_the_length_when_everything_fits(handle):
    fd, _ = handle
    assert write_all(fd, b"a" * CAP) == CAP


def test_write_all_raises_after_the_bytes_that_fit(handle):
    fd, path = handle
    with pytest.raises(LimitReached) as caught:
        write_all(fd, b"a" * 5000)
    assert caught.value.written == CAP
    assert caught.value.limit == CAP
    assert caught.value.errno == errno.EFBIG
    assert path.stat().st_size == CAP


def test_the_exception_sentence_names_both_numbers(handle):
    fd, _ = handle
    with pytest.raises(LimitReached) as caught:
        write_all(fd, b"a" * 5000)
    text = str(caught.value)
    assert "4,096" in text


def test_room_on_an_empty_file_is_the_limit(handle):
    fd, _ = handle
    assert room(fd, CAP) == CAP


def test_room_reaches_zero_at_the_limit(handle):
    fd, _ = handle
    write_up_to(fd, b"a" * CAP)
    assert room(fd, CAP) == 0


def test_room_without_a_limit_is_none(handle):
    fd, _ = handle
    assert room(fd, resource.RLIM_INFINITY) is None


def test_append_writes_what_fits_then_raises(tmp_path):
    target = tmp_path / "app.log"
    with pytest.raises(LimitReached):
        append(str(target), b"a" * 5000)
    assert target.stat().st_size == CAP


def test_append_to_a_missing_file_creates_it(tmp_path):
    target = tmp_path / "new.log"
    assert append(str(target), b"line\n") == 5
    assert target.read_bytes() == b"line\n"


def test_no_bytes_are_written_past_the_limit(handle):
    fd, path = handle
    write_up_to(fd, b"a" * 3000)
    write_up_to(fd, b"b" * 3000)
    assert path.read_bytes() == b"a" * 3000 + b"b" * (CAP - 3000)


def test_the_limit_holds_when_the_file_started_below_it(handle):
    fd, path = handle
    assert write_all(fd, b"a" * 1000) == 1000
    assert write_up_to(fd, b"b" * 4000) == CAP - 1000
    assert path.stat().st_size == CAP
tests for the signal and the chain fslimit/tests/test_diagnose.py
"""The signal, the disposition, and the process tree above this one."""
from __future__ import annotations

import signal

import pytest

from fslimit import disposition, guard, parent_chain, restore


def test_guard_installs_ignoring_and_returns_what_was_there():
    before = signal.getsignal(signal.SIGXFSZ)
    try:
        previous = guard()
        assert previous is before
        assert signal.getsignal(signal.SIGXFSZ) == signal.SIG_IGN
    finally:
        restore(before)


def test_restore_puts_the_disposition_back():
    before = signal.getsignal(signal.SIGXFSZ)
    restore(guard())
    assert signal.getsignal(signal.SIGXFSZ) == before


def test_the_interpreter_ignores_sigxfsz_before_the_program_runs():
    """CPython sets SIG_IGN itself, so the crossing write raises instead of killing."""
    assert signal.getsignal(signal.SIGXFSZ) == signal.SIG_IGN


def test_disposition_answers_one_of_two_words():
    assert disposition() in {"ignored", "default"}


def test_disposition_agrees_with_the_signal_module():
    if signal.getsignal(signal.SIGXFSZ) == signal.SIG_IGN:
        assert disposition() == "ignored"
    else:
        assert disposition() == "default"


def test_parent_chain_starts_at_this_process():
    chain = parent_chain()
    assert chain and chain[0]["pid"] == __import__("os").getpid()
    assert chain[0]["line"].startswith("Max file size")


def test_parent_chain_descends_by_parent_ids():
    chain = parent_chain()
    for parent, child in zip(chain, chain[1:]):
        assert parent["ppid"] == child["pid"]


def test_parent_chain_stops_when_asked():
    assert len(parent_chain(depth=1)) == 1


def test_a_chain_entry_carries_the_four_fields():
    entry = parent_chain(depth=1)[0]
    assert set(entry) == {"pid", "name", "ppid", "line"}


def test_the_limit_row_is_in_bytes():
    assert parent_chain(depth=1)[0]["line"].endswith("bytes")


@pytest.mark.parametrize("depth", [2, 3])
def test_deeper_chains_are_no_longer_than_asked(depth):
    assert len(parent_chain(depth=depth)) <= depth

Appendix B: every probe, the example, and the kernel function

Each numbered probe wrote the record a figure came from, and each is printed whole: 12 files, 1,359 lines, including the child runner they share. The example prints 6 lines from 67 lines of code, and the kernel excerpt is the function that applies the limit, copied from the source at the URL in Section 9. Every fold below starts closed, so open one only to reproduce a number.

the child runner: a limit and a signal disposition per run sandbox/rlimit_child.py
"""Run one short program in a child process with a file-size limit and a chosen signal handling.

The limit belongs to a process, so every measurement that needs one runs in a child: the probe
stays alive whatever the child does, and a child killed by SIGXFSZ is an answer rather than a
lost run.  ``signal_mode`` is set inside the child before the program starts, because the
disposition has to belong to the process that writes:

  * ``default``   - SIG_DFL set explicitly: the kernel's action for SIGXFSZ (terminate);
  * ``inherited`` - the program changes nothing, which means it runs under the disposition
                    CPython sets while it starts (SIG_IGN), whatever the parent passed;
  * ``ignore``    - SIG_IGN: the write returns and raises, instead of the process dying;
  * ``handler``   - a Python function: it runs, then the write returns.
"""
from __future__ import annotations

import json
import os
import pathlib
import resource
import signal
import subprocess
import sys

PREAMBLE = {
    "default": "import signal as _signal; _signal.signal(_signal.SIGXFSZ, _signal.SIG_DFL)\n",
    "inherited": "",
    "ignore": "import signal as _signal; _signal.signal(_signal.SIGXFSZ, _signal.SIG_IGN)\n",
    "handler": (
        "import signal as _signal\n"
        "def _on_xfsz(number, frame):\n"
        "    print('SIGXFSZ-HANDLER', _signal.Signals(number).name)\n"
        "_signal.signal(_signal.SIGXFSZ, _on_xfsz)\n"
    ),
}


def _limit(fsize: int | None):
    def apply() -> None:
        if fsize is not None:
            resource.setrlimit(resource.RLIMIT_FSIZE, (fsize, fsize))
    return apply


def run(source: str, fsize: int | None = None, signal_mode: str = "ignore",
        timeout: float = 60) -> dict:
    """Run ``source`` in a fresh interpreter and describe how the process ended."""
    program = PREAMBLE[signal_mode] + source
    started = os.times()
    try:
        result = subprocess.run([sys.executable, "-c", program], capture_output=True, text=True,
                                timeout=timeout, preexec_fn=_limit(fsize),
                                env={**os.environ, "PYTHONUNBUFFERED": "1"})
    except subprocess.TimeoutExpired as exc:
        return {"returncode": None, "signal": None, "timed_out": True,
                "stdout": (exc.stdout or b"").decode() if isinstance(exc.stdout, bytes)
                else (exc.stdout or ""), "stderr": ""}
    spent = (os.times().children_user + os.times().children_system) - (started.children_user
                                                                     + started.children_system)
    answer = None
    lines = result.stdout.strip().splitlines()
    if lines and lines[-1].startswith("{"):
        try:
            answer = json.loads(lines[-1])
        except json.JSONDecodeError:
            answer = None
    crashed = result.returncode < 0
    return {
        "returncode": result.returncode,
        "signal": signal.Signals(-result.returncode).name if crashed else None,
        "shell_status": 128 - result.returncode if crashed else result.returncode,
        "timed_out": False,
        "answer": answer,
        "stdout": result.stdout.strip()[-400:],
        "stderr": result.stderr.strip()[-400:],
        "cpu_s": round(spent, 4),
    }


def cut(size: int) -> str:
    """A path in /tmp that this call owns, removed by the program that created it."""
    return f"/tmp/fslimit_child_{os.getpid()}_{size}"


def parent_limits() -> dict:
    """The runner's own limits, as the page describes the host it measured on."""
    soft, hard = resource.getrlimit(resource.RLIMIT_FSIZE)
    return {"soft": soft, "hard": hard}


def inherited_disposition() -> str:
    """The SIGXFSZ disposition this process has now, read from its own mask.

    In Python that is SIG_IGN because the interpreter set it, not because the launcher did.
    """
    ignored = int(next(line.split()[1] for line in
                       pathlib.Path("/proc/self/status").read_text().splitlines()
                       if line.startswith("SigIgn:")), 16)
    return "ignored" if ignored & (1 << (signal.SIGXFSZ - 1)) else "default"


if __name__ == "__main__":
    print(json.dumps({"limits": parent_limits(),
                      "inherited_disposition": inherited_disposition(),
                      "signal": signal.Signals(signal.SIGXFSZ).name,
                      "number": signal.SIGXFSZ,
                      "tmp": pathlib.Path("/tmp").is_dir(),
                      "infinity": resource.RLIM_INFINITY}, indent=1))
one record per probe, one arm per condition sandbox/probelib.py
"""Shared helpers for the probes: one record per probe, one arm per condition.

An arm is a label and the runs of one callable. An arm that answers with an errno runs once,
because an errno does not move between runs; an arm that answers with a duration runs five
times so the page can print a median and the range it came from.
"""
from __future__ import annotations

import json
import os
import pathlib
import shutil
import statistics
import tempfile
import time
import traceback

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"


def scratch(prefix: str) -> str:
    """A fresh directory under /tmp, removed by clean()."""
    return tempfile.mkdtemp(prefix=prefix, dir="/tmp")


def clean(path: str) -> None:
    shutil.rmtree(path, ignore_errors=True)


def describe(call) -> dict:
    """Run one call and describe what a caller would receive."""
    try:
        value = call()
        return {"ok": True, "errno": None, "exception": None, "message": None, "value": value}
    except OSError as exc:
        return {"ok": False, "errno": exc.errno, "exception": type(exc).__name__,
                "message": str(exc), "strerror": exc.strerror}
    except Exception as exc:  # noqa: BLE001 - a probe reports what happened, whatever it is
        return {"ok": False, "errno": None, "exception": type(exc).__name__,
                "message": str(exc), "strerror": None}


def arm(label: str, call, repeats: int = 1) -> dict:
    runs = [describe(call) for _ in range(repeats)]
    return {"label": label, "runs": runs}


def timed(label: str, call, repeats: int = 5) -> dict:
    """Repeat a callable that returns (value, seconds) and record every run."""
    runs = []
    for _ in range(repeats):
        try:
            value, seconds = call()
            runs.append({"ok": True, "value": value, "ns": round(seconds * 1e9)})
        except OSError as exc:
            runs.append({"ok": False, "errno": exc.errno, "exception": type(exc).__name__})
    return {"label": label, "runs": runs}


def median_ns(record: dict) -> float:
    return statistics.median([run["ns"] for run in record["runs"]])


def host() -> dict:
    import platform
    import sys

    def read(path: str) -> str:
        try:
            return pathlib.Path(path).read_text().strip()
        except OSError:
            return ""

    return {
        "kernel": platform.release(),
        "python": sys.version.split()[0],
        "machine": platform.machine(),
        "cpus": os.cpu_count(),
        "sh": os.path.realpath("/bin/sh").rsplit("/", 1)[-1],
        "uid": os.getuid(),
        "page_size": os.sysconf("SC_PAGE_SIZE"),
        "umask": oct(os.umask(os.umask(0o022))),
        "libc": " ".join(platform.libc_ver()).strip(),
        "boot_cmdline": read("/proc/cmdline")[:120],
    }


def mount_of(path: str) -> dict:
    """The mount entry that owns a path: filesystem type and options, from /proc/mounts."""
    target = os.path.realpath(path)
    best = None
    for line in pathlib.Path("/proc/mounts").read_text().splitlines():
        fields = line.split()
        if len(fields) < 4:
            continue
        point = fields[1].replace("\\040", " ")
        if target == point or target.startswith(point.rstrip("/") + "/"):
            if best is None or len(point) > len(best[1]):
                best = (fields[2], point, fields[3])
    if best is None:
        return {"fstype": None, "mount": None, "options": None}
    return {"device": None, "fstype": best[0], "mount": best[1], "options": best[2]}


def write(name: str, payload: dict) -> pathlib.Path:
    RESULTS.mkdir(parents=True, exist_ok=True)
    path = RESULTS / name
    path.write_text(json.dumps(payload, indent=1, ensure_ascii=False, default=str) + "\n",
                    encoding="utf-8")
    print("wrote", path, len(json.dumps(payload)))
    return path


def guard(probe: str, body) -> None:
    """Run a probe body and write a record even if it fails, so a failure is visible."""
    started = time.time()
    try:
        body()
    except Exception:  # noqa: BLE001 - the record must say what went wrong
        traceback.print_exc()
        record = {"probe": probe, "failed": True, "seconds": round(time.time() - started, 2)}
        write(f"{probe}_failed.json", record)
        raise
    print(f"{probe} finished in {time.time() - started:.1f} s")
host facts, errno values, limits and mounts sandbox/01_facts.py
"""What this host says about errno 27 and the limit behind it, before anything is written."""
from __future__ import annotations

import errno
import os
import pathlib
import shutil
import resource
import subprocess
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402
import rlimit_child  # noqa: E402

PROBE = "01_facts"


def ulimit_line(shell: str, blocks: str) -> dict:
    """What ``ulimit -f`` sets, and what the kernel then reports as the byte limit."""
    program = (f"ulimit -f {blocks} 2>/dev/null || exit 9\n"
               "grep 'Max file size' /proc/self/limits\n"
               "python3 -c \"import resource;print(resource.getrlimit("
               "resource.RLIMIT_FSIZE)[0])\"")
    result = subprocess.run([shell, "-c", program], capture_output=True, text=True)
    lines = result.stdout.strip().splitlines()
    return {"shell": shell, "blocks": blocks, "returncode": result.returncode,
            "limits_line": lines[0] if lines else "",
            "bytes": int(lines[1]) if len(lines) > 1 and lines[1].isdigit() else None,
            "stderr": result.stderr.strip()[:120]}


def body() -> None:
    numbers = {
        "EFBIG": errno.EFBIG,
        "name_for_27": errno.errorcode[27],
        "message_for_27": os.strerror(27),
        "ENOSPC": errno.ENOSPC,
        "message_for_28": os.strerror(28),
        "EDQUOT": getattr(errno, "EDQUOT", 122),
        "message_for_122": os.strerror(122),
        "EOVERFLOW": errno.EOVERFLOW,
        "message_for_75": os.strerror(errno.EOVERFLOW),
        "EINVAL": errno.EINVAL,
        "message_for_22": os.strerror(errno.EINVAL),
        "SIGXFSZ": int(__import__("signal").SIGXFSZ),
    }
    mounts = [probelib.mount_of("/tmp"), probelib.mount_of("/workspace")]
    numbers["tmp_total_blocks"] = os.statvfs("/tmp").f_blocks
    numbers["tmp_block_size"] = os.statvfs("/tmp").f_frsize
    numbers["tmp_free_bytes"] = os.statvfs("/tmp").f_bavail * os.statvfs("/tmp").f_frsize
    core = resource.getrlimit(resource.RLIMIT_CORE)
    numbers["core_soft"] = core[0]
    numbers["core_hard"] = core[1]
    limits_file = pathlib.Path("/proc/self/limits").read_text().splitlines()
    notes = {
        "limits_line": next(line for line in limits_file if line.startswith("Max file size")),
        "limits_header": limits_file[0],
        "parent": rlimit_child.parent_limits(),
        "inherited_disposition": rlimit_child.inherited_disposition(),
        "ulimit": [ulimit_line(sh, "8") for sh in ("/bin/sh", "/bin/bash")
                   if pathlib.Path(sh).exists()],
        "tools": {name: shutil.which(name) for name in
                  ("prlimit", "fallocate", "truncate", "systemd-run", "docker", "rsync")},
        "mounts": mounts,
        "pid_max": int(pathlib.Path("/proc/sys/kernel/pid_max").read_text()),
        "overlay_note": "the limit is the process's, not the filesystem's",
    }
    arms = [
        probelib.arm("errno_lookup", lambda: {"number": errno.EFBIG,
                                             "name": errno.errorcode[27],
                                             "message": os.strerror(27)}),
        probelib.arm("signal_lookup", lambda: {"name": __import__("signal").Signals(
            __import__("signal").SIGXFSZ).name,
            "number": int(__import__("signal").SIGXFSZ)}),
    ]
    probelib.write(f"{PROBE}.json", {"probe": PROBE, "host": probelib.host(),
                                     "numbers": numbers, "notes": notes, "arms": arms})


if __name__ == "__main__":
    probelib.guard(PROBE, body)
the exact boundary at five limits sandbox/02_boundary.py
"""The boundary itself: a limit of L bytes, a write of exactly L, and the byte after it."""
from __future__ import annotations

import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402
import rlimit_child as child  # noqa: E402

PROBE = "02_boundary"
LIMITS = (0, 1, 1024, 4096, 65536)
REPEATS = 5

EXACT = """
import json, os
path = "{path}"
fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
first = os.write(fd, b"a" * {exact}) if {exact} else 0
after_exact = os.stat(path).st_size
try:
    second = os.write(fd, b"b")
    errno = None
except OSError as exc:
    second = None
    errno = exc.errno
print(json.dumps({{"first": first, "size_after_exact": after_exact, "second": second,
                   "errno": errno, "size": os.stat(path).st_size}}))
os.close(fd)
os.unlink(path)
"""

OVER = """
import json, os
path = "{path}"
fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
try:
    count = os.write(fd, b"a" * {count})
    errno = None
except OSError as exc:
    count = None
    errno = exc.errno
print(json.dumps({{"count": count, "errno": errno, "size": os.stat(path).st_size}}))
os.close(fd)
os.unlink(path)
"""


def repeat(source: str, limit: int, signal_mode: str = "default") -> list[dict]:
    runs = []
    for _ in range(REPEATS):
        answer = child.run(source, fsize=limit, signal_mode=signal_mode)
        payload = answer.get("answer") or {}
        payload.update({"returncode": answer["returncode"], "signal": answer["signal"],
                        "shell_status": answer["shell_status"]})
        runs.append(payload)
    return runs


def body() -> None:
    arms = []
    for limit in LIMITS:
        exact_source = EXACT.format(path=f"/tmp/fslimit_boundary_{limit}", exact=limit)
        arms.append({"label": f"limit:{limit}:exact_then_one", "limit": limit,
                     "runs": repeat(exact_source, limit)})
        arms.append({"label": f"limit:{limit}:exact_then_one:ignored", "limit": limit,
                     "runs": repeat(exact_source, limit, "ignore")})
        over_source = OVER.format(path=f"/tmp/fslimit_over_{limit}", count=max(limit, 0) + 4096)
        arms.append({"label": f"limit:{limit}:single_over", "limit": limit,
                     "runs": repeat(over_source, limit)})
    probelib.write(f"{PROBE}.json", {
        "probe": PROBE, "limits": list(LIMITS), "repeats": REPEATS,
        "signal_mode": "default (SIG_DFL explicitly set) unless the label ends in :ignored",
        "notes": {"rule": "the kernel counts the file's offset after the write against the soft "
                          "limit, before any byte is stored",
                  "over_request": {str(limit): max(limit, 0) + 4096 for limit in LIMITS}},
        "arms": arms})
    for arm in arms:
        first = arm["runs"][0]
        print(f"{arm['label']:34s} {first}")


if __name__ == "__main__":
    probelib.guard(PROBE, body)
four dispositions of SIGXFSZ sandbox/03_signal.py
"""Who survives the signal: four dispositions of SIGXFSZ, and what each one leaves behind."""
from __future__ import annotations

import pathlib
import signal
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402
import rlimit_child as child  # noqa: E402

PROBE = "03_signal"
LIMIT = 1024
REPEATS = 5
MODES = ("inherited", "default", "ignore", "handler")

PROGRAM = """
import json, os
path = "/tmp/fslimit_signal_{mode}"
fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
first = os.write(fd, b"a" * 1024)
try:
    second = os.write(fd, b"b")
    errno = None
except OSError as exc:
    second = None
    errno = exc.errno
print(json.dumps({{"first": first, "second": second, "errno": errno,
                   "size": os.stat(path).st_size}}))
os.close(fd)
os.unlink(path)
"""


def body() -> None:
    arms = []
    for mode in MODES:
        runs = []
        for _ in range(REPEATS):
            answer = child.run(PROGRAM.format(mode=mode), fsize=LIMIT, signal_mode=mode)
            payload = answer.get("answer") or {}
            payload.update({"returncode": answer["returncode"], "signal": answer["signal"],
                            "shell_status": answer["shell_status"],
                            "handler_ran": "SIGXFSZ-HANDLER" in answer["stdout"],
                            "stderr_empty": not answer["stderr"]})
            runs.append(payload)
        arms.append({"label": f"mode:{mode}", "signal_mode": mode, "runs": runs})
    numbers = {"SIGXFSZ": int(signal.SIGXFSZ), "limit": LIMIT,
               "shell_status": 128 + int(signal.SIGXFSZ)}
    probelib.write(f"{PROBE}.json", {
        "probe": PROBE, "numbers": numbers,
        "notes": {
            "sigign_mask": next(line for line in
                                pathlib.Path("/proc/self/status").read_text().splitlines()
                                if line.startswith("SigIgn:")),
            "signal_ignored_at_start": signal.getsignal(signal.SIGXFSZ) == signal.SIG_IGN,
            "inherited": child.inherited_disposition(),
            "modes": {"inherited": "changed nothing: CPython's SIG_IGN is what applies",
                      "default": "SIG_DFL set explicitly in the child",
                      "ignore": "SIG_IGN set in the child",
                      "handler": "a Python function set in the child"},
        },
        "arms": arms})
    for arm in arms:
        print(arm["label"], arm["runs"][0])


if __name__ == "__main__":
    probelib.guard(PROBE, body)
what lands on disk, seven writers sandbox/04_partial.py
"""What lands on disk when the write asks for more than the limit allows."""
from __future__ import annotations

import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402
import rlimit_child as child  # noqa: E402

PROBE = "04_partial"
LIMIT = 4096
REPEATS = 5

ARMS = {
    # One call that asks for more than the whole limit.
    "one_call_5000": """
import json, os
path = "/tmp/fslimit_01"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
returned = os.write(fd, b"a" * 5000)
try:
    again = os.write(fd, b"b"); errno = None
except OSError as exc:
    again = None; errno = exc.errno
print(json.dumps({"returned": returned, "again": again, "errno": errno,
                  "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    # writev: two buffers, the second one crossing the limit.
    "writev_3000_3000": """
import json, os
path = "/tmp/fslimit_02"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
returned = os.writev(fd, [b"a" * 3000, b"b" * 3000])
print(json.dumps({"returned": returned, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    # pwrite at an offset: only the bytes that fit below the limit are stored.
    "pwrite_offset_3000_len_2000": """
import json, os
path = "/tmp/fslimit_03"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
returned = os.pwrite(fd, b"a" * 2000, 3000)
print(json.dumps({"returned": returned, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    # Buffered binary writer: the bytes sit in the buffer until the flush meets the limit.
    "buffered_write_5000": """
import json, os
path = "/tmp/fslimit_04"
handle = open(path, "wb", buffering=8192)
returned = handle.write(b"a" * 5000)
in_buffer = os.stat(path).st_size
try:
    handle.flush(); flush_errno = None
except OSError as exc:
    flush_errno = exc.errno
after_flush = os.stat(path).st_size
try:
    handle.close(); close_errno = None
except OSError as exc:
    close_errno = exc.errno
print(json.dumps({"returned": returned, "in_buffer": in_buffer, "flush_errno": flush_errno,
                  "after_flush": after_flush, "close_errno": close_errno,
                  "size": os.stat(path).st_size}))
os.unlink(path)
""",
    # Text mode: the encoder hands the buffer over at flush time.
    "text_write_5000": """
import json, os
path = "/tmp/fslimit_05"
handle = open(path, "w")
returned = handle.write("a" * 5000)
in_buffer = os.stat(path).st_size
try:
    handle.flush(); flush_errno = None
except OSError as exc:
    flush_errno = exc.errno
size = os.stat(path).st_size
try:
    handle.close(); close_errno = None
except OSError as exc:
    close_errno = exc.errno
print(json.dumps({"returned": returned, "in_buffer": in_buffer, "flush_errno": flush_errno,
                  "size": size, "close_errno": close_errno}))
os.unlink(path)
""",
    # A file larger than the limit, made before the limit applied: an overwrite inside it, a
    # write that ends inside it, and a write that would extend it.
    "overwrite_inside_larger_file": """
import json, os
path = "/tmp/fslimit_06"
before = os.stat(path).st_size
fd = os.open(path, os.O_WRONLY)
inside = os.pwrite(fd, b"b", 0)
crossing_but_inside = os.pwrite(fd, b"b" * 200, 4000)
os.lseek(fd, 0, os.SEEK_END)
try:
    extended = os.write(fd, b"c"); errno = None
except OSError as exc:
    extended = None; errno = exc.errno
after = os.stat(path).st_size
os.close(fd); os.unlink(path)
print(json.dumps({"before": before, "inside": inside, "crossing_but_inside": crossing_but_inside,
                  "extended": extended, "errno": errno, "after": after}))
""",
    # O_APPEND to a file that is already at the limit.
    "append_to_file_at_limit": """
import json, os
path = "/tmp/fslimit_07"
before = os.stat(path).st_size
fd = os.open(path, os.O_WRONLY | os.O_APPEND)
try:
    appended = os.write(fd, b"c"); errno = None
except OSError as exc:
    appended = None; errno = exc.errno
print(json.dumps({"before": before, "appended": appended, "errno": errno,
                  "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
}


def seed() -> None:
    """Two files made without a limit, for the arms that need them."""
    with open("/tmp/fslimit_06", "wb") as handle:
        handle.write(b"a" * 8192)
    with open("/tmp/fslimit_07", "wb") as handle:
        handle.write(b"a" * 4096)


def repeat(source: str) -> list[dict]:
    runs = []
    for _ in range(REPEATS):
        answer = child.run(source, fsize=LIMIT, signal_mode="ignore")
        payload = answer.get("answer") or {}
        payload.update({"returncode": answer["returncode"], "stderr": answer["stderr"][-160:]})
        runs.append(payload)
    return runs


def body() -> None:
    arms = []
    for label, source in ARMS.items():
        seed()
        arms.append({"label": label, "runs": repeat(source)})
    probelib.write(f"{PROBE}.json", {
        "probe": PROBE, "limit": LIMIT, "repeats": REPEATS,
        "notes": {"signal_mode": "ignore, so the crossing write raises instead of killing",
                  "requests": {"one_call": 5000, "writev": [3000, 3000], "pwrite_offset": 3000,
                               "pwrite_length": 2000, "buffered": 5000, "text": 5000,
                               "seed_file": 8192, "crossing_length": 200, "crossing_offset": 4000,
                               "append": 1}},
        "arms": arms})
    for arm in arms:
        print(f"{arm['label']:30s} {arm['runs'][0]}")


if __name__ == "__main__":
    probelib.guard(PROBE, body)
fourteen calls against one limit sandbox/05_surface.py
"""Which calls answer the limit, and what each one leaves behind.

Every call runs in its own child at a limit of 4,096 bytes with SIGXFSZ ignored, so a refusal
comes back as EFBIG and a death comes back as a signal.
"""
from __future__ import annotations

import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402
import rlimit_child as child  # noqa: E402

PROBE = "05_surface"
LIMIT = 4096
REPEATS = 5

ARMS = {
    "os.write:5000": """
import json, os
path = "/tmp/f49_a1"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
try:
    value = os.write(fd, b"a" * 5000); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "os.pwrite:0:5000": """
import json, os
path = "/tmp/f49_a2"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
try:
    value = os.pwrite(fd, b"a" * 5000, 0); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "os.writev:5000": """
import json, os
path = "/tmp/f49_a3"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
try:
    value = os.writev(fd, [b"a" * 4096, b"b" * 904]); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "os.truncate:8192": """
import json, os
path = "/tmp/f49_a4"
with open(path, "wb") as handle:
    handle.write(b"a")
try:
    os.truncate(path, 8192); errno = None
except OSError as exc:
    errno = exc.errno
print(json.dumps({"errno": errno, "size": os.stat(path).st_size}))
os.unlink(path)
""",
    "os.ftruncate:8192": """
import json, os
path = "/tmp/f49_a5"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
os.write(fd, b"a")
try:
    os.ftruncate(fd, 8192); errno = None
except OSError as exc:
    errno = exc.errno
print(json.dumps({"errno": errno, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "os.posix_fallocate:8192": """
import json, os
path = "/tmp/f49_a6"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
try:
    os.posix_fallocate(fd, 0, 8192); errno = None
except OSError as exc:
    errno = exc.errno
print(json.dumps({"errno": errno, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "os.sendfile:8192": """
import json, os
source = "/tmp/f49_source"; target = "/tmp/f49_a7"
out = os.open(target, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
inside = os.open(source, os.O_RDONLY)
try:
    value = os.sendfile(out, inside, 0, 8192); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": os.stat(target).st_size}))
os.close(inside); os.close(out); os.unlink(target)
""",
    "os.copy_file_range:8192": """
import json, os
source = "/tmp/f49_source"; target = "/tmp/f49_a8"
out = os.open(target, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
inside = os.open(source, os.O_RDONLY)
try:
    value = os.copy_file_range(inside, out, 8192); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": os.stat(target).st_size}))
os.close(inside); os.close(out); os.unlink(target)
""",
    "mmap:touch_5000": """
import json, mmap, os
path = "/tmp/f49_mmap"
fd = os.open(path, os.O_RDWR)
handle = mmap.mmap(fd, 8192)
handle[5000] = 65
print(json.dumps({"value": "no fault", "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "pathlib.write_bytes:8000": """
import json, os, pathlib
path = pathlib.Path("/tmp/f49_a9")
try:
    path.write_bytes(b"a" * 8000); errno = None
except OSError as exc:
    errno = exc.errno
print(json.dumps({"errno": errno, "size": os.stat(path).st_size}))
path.unlink()
""",
    "shutil.copyfile:8192": """
import json, os, shutil
try:
    shutil.copyfile("/tmp/f49_source", "/tmp/f49_a10"); errno = None
except OSError as exc:
    errno = exc.errno
size = os.stat("/tmp/f49_a10").st_size
os.unlink("/tmp/f49_a10")
print(json.dumps({"errno": errno, "size": size}))
""",
    "os.lseek:999999": """
import json, os
path = "/tmp/f49_a11"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
try:
    value = os.lseek(fd, 999999, os.SEEK_SET); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "os.write_devnull:5000": """
import json, os
fd = os.open("/dev/null", os.O_WRONLY)
try:
    value = os.write(fd, b"a" * 5000); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": None}))
os.close(fd)
""",
    "os.write_pipe:5000": """
import json, os
read_fd, write_fd = os.pipe()
try:
    value = os.write(write_fd, b"a" * 5000); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": None}))
os.close(read_fd); os.close(write_fd)
""",
}


def seed() -> None:
    with open("/tmp/f49_source", "wb") as handle:
        handle.write(b"s" * 8192)
    with open("/tmp/f49_mmap", "wb") as handle:
        handle.write(b"m" * 8192)


def repeat(source: str) -> list[dict]:
    runs = []
    for _ in range(REPEATS):
        answer = child.run(source, fsize=LIMIT, signal_mode="ignore")
        payload = answer.get("answer") or {}
        payload.update({"returncode": answer["returncode"], "signal": answer["signal"],
                        "stderr_tail": answer["stderr"][-90:]})
        runs.append(payload)
    return runs


def body() -> None:
    seed()
    arms = []
    for label, source in ARMS.items():
        seed()
        arms.append({"label": label, "runs": repeat(source)})
    probelib.write(f"{PROBE}.json", {
        "probe": PROBE, "limit": LIMIT, "repeats": REPEATS,
        "notes": {"requests": {"write": 5000, "pwrite": 5000, "writev": 5000, "truncate": 8192,
                               "ftruncate": 8192, "fallocate": 8192, "sendfile": 8192,
                               "copy_range": 8192, "mmap_offset": 5000, "pathlib": 8000,
                               "copyfile": 8192, "lseek": 999999, "devnull": 5000,
                               "pipe": 5000},
                  "source_file_bytes": 8192,
                  "signal_mode": "ignore",
                  "filesystem": probelib.mount_of("/tmp")["fstype"]},
        "arms": arms})
    for arm in arms:
        first = arm["runs"][0]
        print(f"{arm['label']:28s} {first}")


if __name__ == "__main__":
    probelib.guard(PROBE, body)
six starting offsets sandbox/06_offsets.py
"""The offset arithmetic: where a write may start, and where it is cut.

Same 4,096-byte limit throughout, SIGXFSZ ignored so every refusal is an errno rather than a
dead process.
"""
from __future__ import annotations

import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402
import rlimit_child as child  # noqa: E402

PROBE = "06_offsets"
LIMIT = 4096
REPEATS = 5

ARMS = {
    "seek_2000_write_100": """
import json, os
path = "/tmp/f49_o1"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
os.lseek(fd, 2000, os.SEEK_SET)
value = os.write(fd, b"a" * 100)
print(json.dumps({"value": value, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "seek_4095_write_1": """
import json, os
path = "/tmp/f49_o2"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
os.lseek(fd, 4095, os.SEEK_SET)
value = os.write(fd, b"a")
print(json.dumps({"value": value, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "seek_4095_write_2": """
import json, os
path = "/tmp/f49_o3"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
os.lseek(fd, 4095, os.SEEK_SET)
value = os.write(fd, b"ab")
print(json.dumps({"value": value, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "seek_4096_write_1": """
import json, os
path = "/tmp/f49_o4"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
os.lseek(fd, 4096, os.SEEK_SET)
try:
    value = os.write(fd, b"a"); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "seek_10000_write_1": """
import json, os
path = "/tmp/f49_o5"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
os.lseek(fd, 10000, os.SEEK_SET)
try:
    value = os.write(fd, b"a"); errno = None
except OSError as exc:
    value = None; errno = exc.errno
print(json.dumps({"value": value, "errno": errno, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
    "clip_then_fsync": """
import json, os
path = "/tmp/f49_o6"; fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
value = os.write(fd, b"a" * 5000)
os.fsync(fd)
print(json.dumps({"value": value, "size": os.stat(path).st_size}))
os.close(fd); os.unlink(path)
""",
}


def repeat(source: str) -> list[dict]:
    runs = []
    for _ in range(REPEATS):
        answer = child.run(source, fsize=LIMIT, signal_mode="ignore")
        payload = answer.get("answer") or {}
        payload.update({"returncode": answer["returncode"], "signal": answer["signal"]})
        runs.append(payload)
    return runs


def body() -> None:
    arms = [{"label": label, "runs": repeat(source)} for label, source in ARMS.items()]
    probelib.write(f"{PROBE}.json", {
        "probe": PROBE, "limit": LIMIT, "repeats": REPEATS,
        "notes": {"rule": "a write is cut where its own end offset meets the limit, whatever "
                          "the file's length already is",
                  "offsets": {"seek_then_write": [2000, 100], "last_byte": [4095, 1],
                              "last_two": [4095, 2], "at_limit": [4096, 1],
                              "past_limit": [10000, 1], "clip_then_fsync": 5000}},
        "arms": arms})
    for arm in arms:
        print(f"{arm['label']:24s} {arm['runs'][0]}")


if __name__ == "__main__":
    probelib.guard(PROBE, body)
the module, measured in children sandbox/07_module.py
"""The module, measured where it matters: inside a child whose limit is 4,096 bytes."""
from __future__ import annotations

import os
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402
import rlimit_child as child  # noqa: E402

HERE = pathlib.Path(__file__).resolve().parent.parent
os.environ["PYTHONPATH"] = str(HERE)
PROBE = "07_module"
LIMIT = 4096
REPEATS = 5

ARMS = {
    "raw_write_without_guard": """
import os
fd = os.open("/tmp/f49_m1", os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
os.write(fd, b"a" * 4096)
os.write(fd, b"b")
print('{"value": "survived"}')
""",
    "raw_write_with_guard": """
import json, os
from fslimit import guard
fd = os.open("/tmp/f49_m2", os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
guard()
os.write(fd, b"a" * 4096)
try:
    os.write(fd, b"b"); errno = None
except OSError as exc:
    errno = exc.errno
print(json.dumps({"errno": errno, "size": os.stat("/tmp/f49_m2").st_size}))
os.unlink("/tmp/f49_m2")
""",
    "write_up_to": """
import json, os
from fslimit import write_up_to
fd = os.open("/tmp/f49_m3", os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
value = write_up_to(fd, b"a" * 5000)
print(json.dumps({"value": value, "size": os.stat("/tmp/f49_m3").st_size}))
os.unlink("/tmp/f49_m3")
""",
    "write_all": """
import json, os
from fslimit import LimitReached, write_all
fd = os.open("/tmp/f49_m4", os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
try:
    write_all(fd, b"a" * 5000)
    answer = {"raised": False}
except LimitReached as exc:
    answer = {"raised": True, "written": exc.written, "limit": exc.limit,
              "errno": exc.errno, "sentence": str(exc)}
answer["size"] = os.stat("/tmp/f49_m4").st_size
print(json.dumps(answer))
os.unlink("/tmp/f49_m4")
""",
    "append_at_limit": """
import json, os
from fslimit import LimitReached, append
open("/tmp/f49_m5", "wb").write(b"a" * 4096)
try:
    append("/tmp/f49_m5", b"b")
    answer = {"raised": False}
except LimitReached as exc:
    answer = {"raised": True, "written": exc.written}
answer["size"] = os.stat("/tmp/f49_m5").st_size
print(json.dumps(answer))
os.unlink("/tmp/f49_m5")
""",
    "budget": """
import json
from fslimit import budget
print(json.dumps(budget()))
""",
    "describe": """
import json
from fslimit import describe
print(json.dumps({"sentence": describe(OSError(27, "File too large", "/var/log/app.log"), 4096)}))
""",
    "line": """
import json
from fslimit import line
print(json.dumps({"line": line()}))
""",
}


def repeat(source: str, mode: str = "ignore") -> list[dict]:
    runs = []
    for _ in range(REPEATS):
        answer = child.run(source, fsize=LIMIT, signal_mode=mode)
        payload = answer.get("answer") or {}
        payload.update({"returncode": answer["returncode"], "signal": answer["signal"]})
        runs.append(payload)
    return runs


def body() -> None:
    arms = []
    for label, source in ARMS.items():
        mode = "default" if label == "raw_write_without_guard" else "ignore"
        arms.append({"label": label, "signal_mode": mode, "runs": repeat(source, mode)})
    probelib.write(f"{PROBE}.json", {
        "probe": PROBE, "limit": LIMIT, "repeats": REPEATS,
        "notes": {"package": "fslimit", "import_path": str(HERE)},
        "arms": arms})
    for arm in arms:
        print(f"{arm['label']:26s} {arm['runs'][0]}")


if __name__ == "__main__":
    probelib.guard(PROBE, body)
the cost of reading the limit sandbox/08_cost.py
"""What it costs to ask, 200 calls per run and five runs per arm."""
from __future__ import annotations

import os
import pathlib
import sys
import time

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402

HERE = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(HERE))
from fslimit import budget, line, room  # noqa: E402

PROBE = "08_cost"
CALLS = 200
REPEATS = 5


def timed(call) -> tuple[object, float]:
    started = time.perf_counter()
    for _ in range(CALLS):
        call()
    return None, time.perf_counter() - started


def body() -> None:
    fd = os.open("/tmp/fslimit_cost", os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
    os.write(fd, b"a" * 1024)
    try:
        arms = [
            probelib.timed("getrlimit", lambda: timed(
                lambda: __import__("resource").getrlimit(
                    __import__("resource").RLIMIT_FSIZE)), REPEATS),
            probelib.timed("budget", lambda: timed(budget), REPEATS),
            probelib.timed("ceiling", lambda: timed(
                lambda: __import__("fslimit").ceiling()), REPEATS),
            probelib.timed("line_reads_proc", lambda: timed(line), REPEATS),
            probelib.timed("room_lseek", lambda: timed(lambda: room(fd, 4096)), REPEATS),
            probelib.timed("lseek_only", lambda: timed(
                lambda: os.lseek(fd, 0, os.SEEK_END)), REPEATS),
        ]
    finally:
        os.close(fd)
        os.unlink("/tmp/fslimit_cost")
    probelib.write(f"{PROBE}.json", {
        "probe": PROBE, "calls_per_run": CALLS, "repeats": REPEATS,
        "notes": {"unit": "ns per call, median of five runs of 200 calls"},
        "arms": arms})
    for arm in arms:
        runs = [run["ns"] for run in arm["runs"]]
        print(f"{arm['label']:18s} median {sorted(runs)[len(runs) // 2]:>8,} ns  range "
              f"{min(runs):,}-{max(runs):,}")


if __name__ == "__main__":
    probelib.guard(PROBE, body)
the tree’s own counts and its suite sandbox/09_counts.py
"""Count the tree the page prints, and run its suite, so the page can state both."""
from __future__ import annotations

import json
import pathlib
import re
import subprocess
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402

HERE = pathlib.Path(__file__).resolve().parent.parent
PROBE = "09_counts"


def lines(path: pathlib.Path) -> int:
    return len(path.read_text(encoding="utf-8").rstrip("\n").splitlines())


def body() -> None:
    package = sorted((HERE / "fslimit").glob("*.py"))
    tests = sorted((HERE / "fslimit" / "tests").glob("*.py"))
    probes = sorted((HERE / "sandbox").glob("*.py"))
    example = HERE / "examples" / "fslimit_demo.py"
    result = subprocess.run([sys.executable, "-m", "pytest", "fslimit/tests", "-q",
                             "-p", "no:cacheprovider", "-p", "no:warnings"],
                            cwd=str(HERE), capture_output=True, text=True)
    output = result.stdout + result.stderr
    match = re.search(r"(\d+) passed", output)
    record = {
        "probe": PROBE,
        "pytest_passed": int(match.group(1)) if match else 0,
        "pytest_rc": result.returncode,
        "pytest_tail": output.strip().splitlines()[-1:],
        "package_files": len(package),
        "package_lines": sum(lines(path) for path in package),
        "test_files": len(tests),
        "test_lines": sum(lines(path) for path in tests),
        "probe_files": len(probes),
        "probe_lines": sum(lines(path) for path in probes),
        "example_file_lines": lines(example),
        "package_names": [path.name for path in package],
        "test_names": [path.name for path in tests],
        "probe_names": [path.name for path in probes],
    }
    example_run = subprocess.run([sys.executable, "examples/fslimit_demo.py"], cwd=str(HERE),
                                 capture_output=True, text=True,
                                 env={**__import__("os").environ, "PYTHONPATH": str(HERE)})
    record["example_output_lines"] = len(example_run.stdout.strip().splitlines())
    record["example_rc"] = example_run.returncode
    probelib.write(f"{PROBE}.json", record)
    print(json.dumps({key: value for key, value in record.items() if not key.endswith("names")},
                     indent=1))


if __name__ == "__main__":
    probelib.guard(PROBE, body)
who ignores SIGXFSZ: the launcher or CPython sandbox/10_sigxfsz_origin.py
"""Who ignores SIGXFSZ: the launcher, CPython's own start-up, or the program.

Section 4 needed one answer the disposition table cannot give on its own. A Python child that
changes nothing survives the signal, and "nothing changed" has two possible causes: the parent
passed SIG_IGN down through exec, or the interpreter set it while starting. This probe
separates them by watching a process that is not Python.

The mask in ``/proc/<pid>/status`` is the kernel's answer for a live process, so each arm reads
it from the process that has it: ``/bin/cat``, a C program, or a second Python.
"""
from __future__ import annotations

import pathlib
import re
import resource
import shutil
import signal
import subprocess
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib  # noqa: E402
import rlimit_child as child  # noqa: E402

PROBE = "10_sigxfsz_origin"
LIMIT = 4096
BYTES = 8192
REPEATS = 5

# Set both dispositions to the kernel's default, then become something else. Exec keeps SIG_IGN
# and resets handlers, so this is the only way to hand a child a clean slate.
RESET_THEN_EXEC = """
import os, signal, sys
for name in ("SIGXFSZ", "SIGPIPE"):
    signal.signal(getattr(signal, name), signal.SIG_DFL)
os.execv(sys.argv[1], sys.argv[1:])
"""

# What Python reports about itself once it is running, after any start-up work of its own.
REPORT_PYTHON = """
import signal, sys
print(signal.getsignal(signal.SIGXFSZ), signal.getsignal(signal.SIGPIPE))
print(next(line.split()[1] for line in open("/proc/self/status") if line.startswith("SigIgn:")))
sys.exit(0)
"""

MASK_LINE = re.compile(r"SigIgn:\s*([0-9a-f]+)")


def mask_of(text: str) -> dict:
    """The mask the kernel printed, decoded for the two signals that matter here."""
    match = MASK_LINE.search(text)
    if match is None:
        return {"mask": None, "sigxfsz": "unknown", "sigpipe": "unknown"}
    bits = int(match.group(1), 16)
    return {"mask": match.group(1),
            "sigxfsz": "ignored" if bits & (1 << (signal.SIGXFSZ - 1)) else "default",
            "sigpipe": "ignored" if bits & (1 << (signal.SIGPIPE - 1)) else "default"}


def apply_limit(fsize: int | None):
    def apply() -> None:
        if fsize is not None:
            resource.setrlimit(resource.RLIMIT_FSIZE, (fsize, fsize))
    return apply


def one(argv: list[str], fsize: int | None = None, mask: bool = False) -> dict:
    """Run a command once and describe the process that came back."""
    result = subprocess.run(argv, capture_output=True, text=True, timeout=60,
                            preexec_fn=apply_limit(fsize))
    crashed = result.returncode < 0
    record = {"returncode": result.returncode,
              "signal": signal.Signals(-result.returncode).name if crashed else None,
              "shell_status": 128 - result.returncode if crashed else result.returncode,
              "stderr_empty": not result.stderr.strip()}
    if mask:
        record.update(mask_of(result.stdout))
    elif result.returncode == 0:
        bits, ignored = result.stdout.split()[:2]
        record.update({"sigxfsz": "ignored" if bits == "1" else "default",
                       "sigpipe": "ignored" if ignored == "1" else "default"})
    return record


def repeated(argv: list[str], mask: bool = False) -> list[dict]:
    return [one(argv, mask=mask) for _ in range(REPEATS)]


def body() -> None:
    cat = ["/bin/cat", "/proc/self/status"]
    reset = [sys.executable, "-c", RESET_THEN_EXEC]
    report = [sys.executable, "-c", REPORT_PYTHON]

    arms = [
        {"label": "this process, a running CPython",
         "runs": [{**mask_of(pathlib.Path("/proc/self/status").read_text()),
                   "python": sys.version.split()[0]}]},
        {"label": "/bin/cat, subprocess's default restore_signals=True", "runs": repeated(cat, True)},
        {"label": "/bin/cat, restore_signals=False",
         "runs": [mask_of(subprocess.run(cat, capture_output=True, text=True,
                                         restore_signals=False).stdout)
                  for _ in range(REPEATS)]},
        {"label": "python3, launcher had SIG_DFL", "runs": repeated(reset + report)},
        {"label": "/bin/cat, launcher had SIG_DFL", "runs": repeated(reset + cat, True)},
    ]

    dd = shutil.which("dd") or "/bin/dd"
    target = f"/tmp/fslimit_origin_{PROBE}.bin"
    arm = {"label": f"dd writing {BYTES:,} bytes under a {LIMIT:,}-byte limit", "runs": []}
    for _ in range(REPEATS):
        pathlib.Path(target).unlink(missing_ok=True)
        record = one([dd, "if=/dev/zero", f"of={target}", "bs=1024", "count=8"], fsize=LIMIT)
        record["file_size"] = pathlib.Path(target).stat().st_size
        arm["runs"].append(record)
    pathlib.Path(target).unlink(missing_ok=True)
    arms.append(arm)

    write_program = (
        "import json, os\n"
        "path = '/tmp/fslimit_origin_py'\n"
        "fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)\n"
        f"os.write(fd, b'a' * {LIMIT})\n"
        "try:\n"
        "    os.write(fd, b'b')\n"
        "    print(json.dumps({'errno': None}))\n"
        "except OSError as exc:\n"
        "    print(json.dumps({'errno': exc.errno}))\n"
        "os.close(fd)\n"
        "os.unlink(path)\n")
    for mode, label in (("inherited", f"python3, {LIMIT:,}-byte limit, nothing changed"),
                        ("default", f"python3, {LIMIT:,}-byte limit, SIG_DFL set")):
        arm = {"label": label, "runs": []}
        for _ in range(REPEATS):
            answer = child.run(write_program, fsize=LIMIT, signal_mode=mode)
            arm["runs"].append({"returncode": answer["returncode"],
                                "shell_status": answer["shell_status"],
                                "signal": answer["signal"],
                                "errno": (answer.get("answer") or {}).get("errno"),
                                "stderr_empty": not answer["stderr"].strip()})
        arms.append(arm)

    probelib.write(f"{PROBE}.json", {
        "probe": PROBE,
        "numbers": {"SIGXFSZ": int(signal.SIGXFSZ), "SIGPIPE": int(signal.SIGPIPE),
                    "limit": LIMIT, "bytes": BYTES,
                    "shell_status": 128 + int(signal.SIGXFSZ)},
        "notes": {
            "source": "Modules/signalmodule.c, CPython v3.12.16 (Python 3.10 and later)",
            "installer": "signal_install_handlers(), called from _PySignal_Init()",
            "install_url": ("https://github.com/python/cpython/blob/v3.12.16/"
                            "Modules/signalmodule.c#L1908-L1918"),
            "history": ("initsigs() in Python/pylifecycle.c through Python 3.7 "
                        "(Python/pythonrun.c in Python 2.7), init_signals() in Python 3.8 "
                        "and 3.9, signal_install_handlers() from Python 3.10"),
            "history_urls": [
                "https://github.com/python/cpython/blob/v2.7.18/Python/pythonrun.c#L1801-L1810",
                "https://github.com/python/cpython/blob/v3.7.17/Python/pylifecycle.c#L2300-L2310",
                "https://github.com/python/cpython/blob/v3.8.0/Python/pylifecycle.c#L2303-L2313",
            ],
            "restore": ("PyOS_setsig(SIGXFSZ, SIG_DFL) in _Py_RestoreSignals(), called by "
                        "_posixsubprocess.c in the child before exec, not at shutdown"),
            "restore_url": ("https://github.com/python/cpython/blob/v3.12.16/"
                            "Modules/signalmodule.c#L1940-L1952"),
            "subprocess_url": ("https://github.com/python/cpython/blob/v3.12.16/"
                               "Modules/_posixsubprocess.c#L665"),
            "versions_checked": ["2.7.18", "3.5.10", "3.6.15", "3.7.17", "3.8.0", "3.9.0",
                                 "3.10.0", "3.12.16"],
            "arms": {
                "this process, a running CPython": "the mask CPython left in place",
                "/bin/cat, subprocess's default restore_signals=True":
                    "subprocess put SIG_DFL back before it executed the child",
                "/bin/cat, restore_signals=False": "SIG_IGN came through exec from this Python",
                "python3, launcher had SIG_DFL": "the interpreter set SIG_IGN itself",
                "/bin/cat, launcher had SIG_DFL": "nothing else sets it",
                f"dd writing {BYTES:,} bytes under a {LIMIT:,}-byte limit":
                    "a C writer that never ignored the signal",
                f"python3, {LIMIT:,}-byte limit, nothing changed":
                    "the same crossing write in Python: errno 27",
                f"python3, {LIMIT:,}-byte limit, SIG_DFL set":
                    "the same crossing write after one line: SIGXFSZ",
            },
        },
        "arms": arms})
    for record in arms:
        print(record["label"], record["runs"][0])


if __name__ == "__main__":
    probelib.guard(PROBE, body)
the example whose output Section 7 prints examples/fslimit_demo.py
"""One small table: the same 4,096-byte limit, four ways of meeting it.

Run it with ``python3 examples/fslimit_demo.py``. Each child starts with its own copy of the
limit, so the demo never changes the limit of the shell that started it.
"""
from __future__ import annotations

import json
import resource
import subprocess
import sys

LIMIT = 4096


def child(source: str, signal_mode: str) -> dict:
    preamble = {"default": "import signal;s=signal\ns.signal(s.SIGXFSZ, s.SIG_DFL)\n",
                "ignore": "import signal;s=signal\ns.signal(s.SIGXFSZ, s.SIG_IGN)\n"}[signal_mode]
    answer = subprocess.run([sys.executable, "-c", preamble + source], capture_output=True,
                            text=True, preexec_fn=lambda: resource.setrlimit(
                                resource.RLIMIT_FSIZE, (LIMIT, LIMIT)))
    outcome = answer.returncode if answer.returncode >= 0 else f"signal {-answer.returncode}"
    return {"outcome": outcome, "stdout": answer.stdout.strip().splitlines()[-1:] or [""]}


RAW = """
import os
fd = os.open("/tmp/fslimit_demo_raw", os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
os.write(fd, b"a" * 4096)
try:
    os.write(fd, b"b")
    print("survived")
except OSError as exc:
    print("EFBIG after 4,096 bytes" if exc.errno == 27 else f"errno {exc.errno}")
os.unlink("/tmp/fslimit_demo_raw")
"""

MODULE = """
import os, sys
from fslimit import budget, disposition, write_up_to
fd = os.open("/tmp/fslimit_demo_module", os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o644)
try:
    write_up_to(fd, b"a" * 5000)
    print("4,096 bytes written, no signal")
finally:
    os.close(fd)
    os.unlink("/tmp/fslimit_demo_module")
"""


def main() -> None:
    sys.path.insert(0, ".")
    print(f"{'condition':38s} {'answer'}")
    first = child(RAW, "default")
    print(f"{'limit 4,096, SIGXFSZ default':38s} {first['outcome']}")
    second = child(RAW, "ignore")
    print(f"{'limit 4,096, SIGXFSZ ignored':38s} {second['stdout'][0]}")
    third = child(MODULE, "ignore")
    print(f"{'fslimit.write_up_to':38s} {third['stdout'][0]}")
    from fslimit import budget, disposition  # noqa: E402 - imported here so the child path is clear
    print(f"{'fslimit.budget (this process)':38s} "
          + json.dumps(budget()).replace('"', ""))
    print(f"{'fslimit.disposition (this process)':38s} {disposition()}")


if __name__ == "__main__":
    main()
the kernel function that applies the limit examples/read_write_limit.c
int generic_write_check_limits(struct file *file, loff_t pos, loff_t *count)
{
	struct inode *inode = file->f_mapping->host;
	loff_t max_size = inode->i_sb->s_maxbytes;
	loff_t limit = rlimit(RLIMIT_FSIZE);

	if (limit != RLIM_INFINITY) {
		if (pos >= limit) {
			send_sig(SIGXFSZ, current, 0);
			return -EFBIG;
		}
		*count = min(*count, limit - pos);
	}

	if (!(file->f_flags & O_LARGEFILE))
		max_size = MAX_NON_LFS;

	if (unlikely(pos >= max_size))
		return -EFBIG;

	*count = min(*count, max_size - pos);

	return 0;
}

Going further

TechBobby Engineering. Appendix A prints the module and its 36 tests; Appendix B prints every probe behind a figure in this page, the example, and the kernel function the limit lives in.


Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.