11.4 Files, Sockets, Pipes, and Descriptors
The operating system provides a common abstraction for I/O: the file descriptor. Files, network sockets, and pipes are all file descriptors. Many R connections are built on top of this layer. Understanding descriptors explains why forked workers inherit open connections, and why a child should leave an inherited connection alone and open its own.
11.4.1 Mental model
A file descriptor is an integer handle to an open resource. File descriptor 0 is standard input. Descriptor 1 is standard output. Descriptor 2 is standard error. Other descriptors are opened by the program.
Three common kinds of resource use descriptors: files on disk, sockets for network communication, and pipes for inter-process communication. The same read and write calls work on all three, and files, pipes and stream sockets all carry plain byte streams.
The kernel maintains a file descriptor table for each process. The table maps integers to open resources. When a process creates or opens a resource, the kernel assigns the lowest unused integer and enters the resource in the table.
11.4.2 Mechanism
Files and file I/O
A file is a byte stream stored on disk. Opening a file returns a file descriptor. The open file has a current position. Reading returns the bytes stored from that position onward, and writing stores bytes at that position, overwriting what was there unless the file was opened in append mode. Each read or write advances the position.
# R code
f <- file("data.txt", "r") # open, returns connection
data <- readLines(f) # read from connection
close(f) # close connectionInternally, R’s file() connection opens the file with the C library’s fopen, which calls the open system call. The connection keeps the C library’s FILE pointer, and the file descriptor sits inside it. Reading through the connection ends in read calls on that descriptor, and closing the connection closes it.
Seeking moves the current position. A program can seek backward and read data again, or seek to the end and append new data. Files are random access. You do not have to read sequentially.
File descriptors have flags. Files can be opened read-only, write-only, or read-write. Files can be opened in append mode, where all writes go to the end. Files can be opened to bypass the kernel’s page cache (direct I/O, O_DIRECT on Linux) for special workloads.
Sockets and network I/O
A socket is an endpoint for network communication. Two sockets on different machines can connect and exchange bytes. Stream sockets, the TCP kind, behave as byte streams, similar to files. A read returns the next bytes sent. A write sends bytes to the remote end.
Unlike a pipe, a socket is bidirectional. A socket can send and receive. Both ends of a socket see the bytes the other sent. The kernel buffers bytes in transit. The receiver’s read gets bytes from this buffer.
Sockets have addressing. A socket binds to an address (IP and port). A client connects to that address. The connection is established. Both sides can send and receive.
R’s parallel package uses sockets for PSOCK clusters. The parent listens on a port, and each worker it starts connects back to it. The parent sends tasks as serialized bytes. The worker sends results as serialized bytes.
A socket that crosses a network pays network latency. A socket between two processes on one machine never leaves the kernel, which is how PSOCK workers on a laptop talk to their parent. Because sockets also work across machines, they are the standard for remote computation.
Pipes and inter-process communication
A pipe connects two processes. It is a one-way byte stream. One process writes. The other reads. The kernel buffers bytes. When one process writes and the other is not reading, the bytes accumulate in the kernel buffer. When the buffer is full, the writer blocks. When the reader reads, it removes bytes from the buffer and the writer unblocks.
Pipes are created with pipe(), which returns two file descriptors: one for reading and one for writing. Only the writer can write to the write end. Only the reader can read from the read end.
A common pattern is fork and pipe. The parent creates a pipe before forking. The child inherits both ends of the pipe. The parent closes the write end and reads the read end. The child closes the read end and writes the write end. The child’s output flows to the parent through the pipe.
int fds[2];
pipe(fds);
if (fork() == 0) {
close(fds[0]); // child: close read end
dup2(fds[1], STDOUT_FILENO); // child: redirect stdout to write end
execve("./program", args, env);
} else {
close(fds[1]); // parent: close write end
FILE* f = fdopen(fds[0], "r");
// read child's output from f
}R’s pipe() connection uses the same pattern. On Unix, R’s own R_popen_pg creates the pipe, forks, moves the child into a new process group, and runs the command through /bin/sh -c (src/unix/sys-unix.c).
In the fork-and-pipe pattern above, the child writes and the parent reads. The kernel buffer sits between them and blocks whichever side gets ahead.
Blocking and non-blocking
By default, read and write are blocking. A read on an empty pipe blocks the reader. A write to a full pipe blocks the writer. The process sleeps until data arrives or space becomes available.
Non-blocking I/O never blocks. A read on an empty pipe fails at once with the error EAGAIN, and so does a write to a full pipe. (A read that returns zero bytes means end of file: every write end has been closed.) Event-driven programs pair non-blocking descriptors with a readiness call such as poll, select or Linux’s epoll. One loop waits on many descriptors, handles whichever are ready, and goes back to waiting. This is cheaper than creating a thread per descriptor.
File descriptor inheritance in fork
When a process forks, the child inherits copies of the parent’s file descriptor table. Each copy refers to the same open file as the parent’s descriptor, with the same file offset. This is both useful and dangerous.
If the parent has an open database connection, the child inherits it. The child can use the same connection. But if both parent and child write to the connection, the writes interleave. If both read from it, each byte goes to whichever process reads first, so each sees an unpredictable part of the stream. Race conditions result.
The standard practice is for the child to close the descriptors it does not need. Closing a descriptor in the child leaves the parent’s copy open. Closing a connection through its client library is a different matter: a database client’s disconnect call can first send the server a message that ends the session, and the parent is still using that session. PostgreSQL’s client library documentation advises against using a connection in a forked child at all. A worker that needs the database should open its own connection.
After fork, parent and child share file descriptors. Writes from both can interleave. The standard solution is for the child to close the descriptors only the parent needs and to open its own connections.
11.4.3 R connections
Many GNU R connections wrap an operating system resource. file() holds a C FILE pointer from fopen, pipe() one for the pipe to its child process, and socketConnection() a socket descriptor. Others wrap no descriptor at all: textConnection() reads from a character vector and rawConnection() from a raw vector. Each connection object also records metadata such as its description and open mode.
R provides functions to open, read, and close connections. file() opens a file. socketConnection() opens a socket. pipe() opens a pipe. All return a connection object.
Connections can be text or binary. Text connections interpret newlines. Binary connections return raw bytes.
File connections inherit the C library’s buffering. Writes collect in a buffer that is flushed when it fills, when flush() is called, and when the connection is closed. This reduces system call overhead.
Connections are built on file descriptors but present a higher-level abstraction. Most R code does not need to know about descriptors. Connections hide the details.
But when forking workers, connections become important. Inheriting a database connection is a hazard. The child should neither use nor close the inherited connection, and should open its own.
11.4.4 Descriptors in other systems
Unix and Unix-like systems (Linux, macOS, BSD) all provide file descriptors as the abstraction for I/O. The interface is standard: open, read, write, close. Different resource types (files, sockets, pipes) behave mostly identically through descriptors.
Windows provides a different abstraction: handles. Handles play the role of file descriptors with a different API. Each kind of resource has its own creation call (CreateFile, CreatePipe, and Winsock’s socket), and Winsock sockets are not C runtime file descriptors. On Windows, PSOCK clusters run over Winsock sockets.
11.4.5 Tradeoffs
File descriptors are a simple, uniform abstraction. Any resource can be read and written. That uniformity is what makes pipe and fork compose.
But descriptors carry state. An open file tracks the current position. If two processes hold descriptors for the same open file, as they do after fork, they share the position, so seeking in the parent moves the child’s position too. This is usually unexpected.
Buffering adds complexity. Most reads from a buffered connection trigger no system call, because the buffer serves them from memory. Writes to a buffered connection accumulate in the buffer. Buffering improves performance but adds subtle timing effects.
Further reading
open(2)<https://man7.org/linux/man-pages/man2/open.2.html>,read(2)<https://man7.org/linux/man-pages/man2/read.2.html> andwrite(2)<https://man7.org/linux/man-pages/man2/write.2.html> manual pages.pipe(2)<https://man7.org/linux/man-pages/man2/pipe.2.html> andpipe(7)<https://man7.org/linux/man-pages/man7/pipe.7.html> manual pages.pipe(7)covers pipe capacity and non-blocking reads and writes.socket(2)manual page <https://man7.org/linux/man-pages/man2/socket.2.html>.- Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces <https://pages.cs.wisc.edu/~remzi/OSTEP/>. Free online. See the chapters “I/O Devices”, “Interlude: Files and Directories” and “File System Implementation”.
- Stevens, W. R. and Rago, S. A. (2013). Advanced Programming in the UNIX Environment, 3rd edition <https://www.pearson.com/en-us/subject-catalog/p/advanced-programming-in-the-unix-environment/P200000000628/9780321638007>. Addison-Wesley. Chapter 3 covers file I/O.
- PostgreSQL documentation, Database Connection Control Functions <https://www.postgresql.org/docs/current/libpq-connect.html>, which warns against forking a process with open libpq connections.
- R Core Team, “R Data Import/Export”, chapter Connections <https://cran.r-project.org/doc/manuals/r-release/R-data.html#Connections>.