File descriptors and errno
Quick answer
A file descriptor is a small nonnegative integer in a process that identifies an open resource. Use open, read, write and close to work with files, pipes and other descriptor-backed resources; check the result of every operation.
Descriptor zero is a valid success result for an open operation when that descriptor is available. Check the documented failure sentinel before reading errno; a previous error value can remain after a successful operation. Track descriptor ownership and close it when finished.
Prepare the practice environment
Run python3 lab-fixtures/syscalls/setup.py from the extracted root as an ordinary user. Enter the printed fresh private path and check pwd. Use fresh fixtures, Bash with set -e -o pipefail, LC_ALL=C and umask 077. Run each snippet in a separate Bash process, not your interactive shell. Examples use Python 3 standard-library wrappers on Linux, private files, bounded child processes and local socketpairs. No root or external network is needed. Optional strace inspection requires an authorized environment. Review the lab guide.
Prerequisites
Review: Kernel configuration and release lifecycle, Testing and debugging shell scripts.
How it works
In C, open returns a descriptor or -1; read returns the count of bytes read, zero at end of a regular file, or -1 on error. write returns the number accepted, which can be less than requested. errno is meaningful after an indicated error, not after an arbitrary successful call. Handle short transfers, EINTR and nonblocking EAGAIN according to the operation. Close releases a descriptor, not necessarily the underlying object; dup shares an open file description and its offset. On Linux do not blindly retry a failed close: the number may already have been released. O_CLOEXEC prevents unwanted descriptor inheritance across exec. Python os wrappers raise OSError with an errno field and may retry interrupted calls; Python creates non-inheritable descriptors by default. Examples use Python 3 as a compact interface to Linux behavior, not as an exact syscall trace. Read open(2), read(2), write(2), close(2) and errno(3); C, Go and Rust tracks provide language-specific APIs.
Try the examples
python3 - <<'PYCODE'import osfd = os.open('message.txt', os.O_RDONLY)try: first = os.read(fd, 2) second = os.read(fd, 16) end = os.read(fd, 16) assert (first, second, end) == (b'he', b'llo\n', b'') print(first.decode() + second.decode().strip() + '; EOF')finally: os.close(fd)PYCODERead a small prefix, the remaining bytes, then EOF. A zero-byte result with a positive request means EOF here.
Expected stdout:
hello; EOFpython3 - <<'PYCODE'import os, tempfilewith tempfile.TemporaryFile(dir='.') as f: fd = f.fileno() data = memoryview(b'abc') while data: n = os.write(fd, data) if n == 0: raise RuntimeError('no progress') data = data[n:] os.lseek(fd, 0, os.SEEK_SET) assert os.read(fd, 3) == b'abc' print('write verified')PYCODEAdvance by the returned byte count, then reposition and verify. The temporary file owns the descriptor and closes it automatically.
Expected stdout:
write verifiedpython3 - <<'PYCODE'import os, errnotry: fd = os.open('absent.txt', os.O_RDONLY)except OSError as e: assert e.errno == errno.ENOENT print('ENOENT handled')else: os.close(fd) raise AssertionError('expected missing file')PYCODEThe expected error is checked symbolically rather than relying on localized diagnostic text.
Expected stdout:
ENOENT handledCommon mistakes
Do not assume read or write transfers the full buffer, or inspect errno after success. Do not use a descriptor after close; its integer can be reused.
Practice
Change the read chunk to one byte, collect chunks until EOF and verify hello plus newline. Explain why the write loop advances by the returned count.
Related references
Study: strace. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
File descriptors and errno — Knowledge Check
Apply Linux systems programming interfaces to concrete local examples.
What is a descriptor?
What is a zero read on this regular file with positive count?
What if write returns fewer bytes than requested?
What does ENOENT identify in the sample?