Pipes & Named Pipes (FIFO)

Learn how anonymous pipes connect related processes and named pipes (FIFOs) enable communication between unrelated processes in Unix/Linux systems.

published: reading time: 34 min read author: Geek Workbench updated: November 24, 2026
Quick Summary

Learn how anonymous pipes connect related processes and named pipes (FIFOs) enable communication between unrelated processes in Unix/Linux systems.

Pipes & Named Pipes (FIFO)

Shell pipelines such as ls | grep "error" use pipes. A pipe connects a writer to a reader through a kernel-managed byte stream. Its buffer, EOF, and blocking behavior matter when a pipeline stalls or a reader appears stuck.

Introduction

On POSIX systems, a pipe is a unidirectional byte stream: data written at one end can be read at the other, but the stream has no message boundaries. The kernel buffers a limited amount of data while readers and writers run. Buffer size and internal details vary by operating system and kernel. A pipe is not a file, so its contents are not durable.

Anonymous pipes are created using the pipe() system call and exist only as kernel objects; there is no filesystem path to open. Processes usually share the descriptors through fork() inheritance or another descriptor handoff.

Named pipes, also known as FIFOs (First In, First Out), have a filesystem entry created with mkfifo(). That entry remains until it is unlinked, but it stores no messages: the kernel passes bytes through a temporary buffer while processes have the FIFO open. Any process with access to the path can open it, regardless of ancestry.

Anonymous pipes are commonly passed to related processes through fork() and descriptor inheritance. FIFOs let independently started processes rendezvous through a shared path. On POSIX systems, both carry byte streams; if an application needs message framing, it must add its own delimiter or length field.

When to Use / When Not to Use

Use anonymous pipes when:

  • You have a parent-child or sibling process relationship
  • You want to stream data between a filter command and its input (shell pipelines)
  • You need a simple, low-overhead one-directional channel
  • You can pass the pipe descriptors to the processes that need them

Use named pipes when:

  • You need to communicate between unrelated processes
  • You need independently started processes to rendezvous by a local path (the FIFO name persists, but buffered data does not)
  • You need multiple writers or multiple readers for the same channel
  • You need to coordinate between processes that are started independently
  • You want to debug communication between two long-running processes

Do not use pipes when:

  • You need bidirectional communication (use a socket pair instead)
  • You need to persist data across system reboots (use a regular file)
  • You need to seek within the data (pipes are stream-oriented, not random access)
  • You want to communicate between machines (use TCP/UDP sockets)
  • You need message boundaries preserved with multiple discrete messages (use message queues)

Architecture or Flow Diagram

Anonymous Pipe Creation: pipe() System Call

The pipe() system call creates an anonymous pipe and returns two file descriptors: pipefd[0] for reading and pipefd[1] for writing. The pipe has no filesystem name. Its buffering and capacity are implementation details, so code should not depend on a particular size. Calling pipe() twice creates two separate channels.

The diagram shows creation only; no data has flowed yet. Pipe ends are blocking by default on POSIX systems. Set O_NONBLOCK with fcntl() when nonblocking reads or writes are needed.

graph LR
    A[Parent process calls pipe] --> B[Kernel creates pipe buffer<br>and two file descriptors]
    B --> C[fd0 = read end, fd1 = write end]

Fork Pattern

Anonymous pipes become useful when you combine them with fork(). The sequence matters: first the parent calls pipe() to create the buffer and two file descriptors, then it calls fork() to create a child. When fork() returns, both parent and child have a copy of the file descriptor table — meaning both now hold references to both ends of the pipe. This is where things go wrong for most developers. Having both ends open in both processes creates a bidirectional channel, which is almost never what you want.

The standard pattern for unidirectional flow is for each side to close the end it does not use. The parent keeps the write end (pipefd[1]) and closes the read end (pipefd[0]). The child does the opposite — keeps the read end, closes the write end. Once the unneeded ends are closed, the pipe becomes a clean one-way channel. The diagram above shows this: the parent writes to fd1, the child reads from fd0, and data flows in one direction.

Both processes’ descriptors refer to the same pipe. Close unused ends in each process: a reader sees EOF only after every open write end has been closed and buffered bytes have been read. An inherited write descriptor left open can therefore keep the reader waiting.

graph LR
    C[fd0 = read end, fd1 = write end] --> D[Parent forks child process]
    D --> E[Child inherits file descriptors]
    E --> F[Parent closes read end<br>Child closes write end]
    F --> G[Data flows: Parent writes to fd1<br>Child reads from fd0]

Named Pipe Creation

Named pipes (FIFOs) get around the ancestry requirement that makes anonymous pipes limiting. An anonymous pipe lives only in kernel memory and can only be reached through inherited file descriptors. A FIFO is a filesystem entry that any process can open by path. mkfifo() takes a path and a mode and returns 0 on success. Where pipe() creates something referenced by descriptors, mkfifo() creates something ls can show you.

The mode argument sets access, subject to the process umask. For example, mkfifo("/tmp/my_fifo", 0660) requests owner and group access. If the FIFO already exists, mkfifo() fails with EEXIST. The filesystem entry stays until unlink(), but bytes sent through it are held in the kernel buffer, not in the filesystem.

After mkfifo(), processes open the shared path. With blocking open(), a read-only open waits for a writer and a write-only open waits for a reader. With O_NONBLOCK, a read-only open succeeds without a writer; a write-only open fails with ENXIO if no reader is present. Linux permits O_RDWR on a FIFO, but POSIX leaves that behavior undefined, so portable code should not rely on it.

graph LR
    H[Process calls mkfifo] --> I[Kernel creates FIFO file<br>in filesystem]
    I --> J[Any process with path<br>can open FIFO for R/W]

FIFO Reader/Writer Connection

With blocking opens, a reader waits until a writer opens the FIFO, and a writer waits until a reader opens it. Starting either process first is fine; it waits until the other arrives. It becomes a deadlock only if the same process or a coordinated set of processes waits for an event that cannot occur.

For nonblocking mode, a read-only open succeeds even if no writer is connected; a read may return 0 while no writer is open. A write-only nonblocking open fails with ENXIO until a reader has opened the FIFO. Handle those states explicitly. Linux also permits O_RDWR, but POSIX does not define that mode for FIFOs, and keeping the local write end open can prevent EOF from reaching the reader.

Once connected, FIFO reads and writes follow the same byte-stream semantics as pipes. A blocking read waits when the buffer is empty and writers remain open; a blocking write waits when the buffer is full. select() or poll() can wait for readiness.

graph LR
    K[Reader process] --> L[Blocks on open FIFO until writer connects]
    M[Writer process] --> L
    L --> N[Both sides now communicate]

Core Concepts

Anonymous Pipe Creation via pipe()

The pipe() system call creates an anonymous pipe and returns two file descriptors:

#include <unistd.h>

int pipefd[2];
if (pipe(pipefd) == -1) {
    perror("pipe");
    exit(1);
}
// pipefd[0] = read end
// pipefd[1] = write end

pipe() gives the process two descriptors for the read and write ends. Buffer capacity is set by the operating system and can vary with kernel version and system limits. On Linux, F_GETPIPE_SZ reports a pipe’s capacity; do not assume a fixed default across systems.

The Fork Pattern

Anonymous pipes are almost always used with fork(). When a process forks, its file descriptor table is duplicated, so the child inherits the pipe’s file descriptors. This creates a situation where both parent and child have both ends of the pipe open — which is usually wrong. The standard pattern is for one side to close the end it does not need:

int pipefd[2];
pipe(pipefd);

pid_t pid = fork();
if (pid == 0) {
    // Child process — reads from pipe
    close(pipefd[1]);  // Close write end
    char buf[128];
    read(pipefd[0], buf, sizeof(buf));
    close(pipefd[0]);
} else {
    // Parent process — writes to pipe
    close(pipefd[0]);  // Close read end
    write(pipefd[1], "hello child", sizeof("hello child") - 1);
    close(pipefd[1]);
}

Pipe capacity, blocking, and PIPE_BUF

Every pipe and FIFO has finite capacity. If a blocking writer fills the buffer, it waits for a reader to make room. This is backpressure: a slow consumer eventually slows the producer. With O_NONBLOCK, an operation that cannot proceed returns promptly; callers must handle EAGAIN and partial writes. Capacity is OS- and kernel-dependent. Linux provides F_GETPIPE_SZ and F_SETPIPE_SZ; applications should still work without assuming a particular capacity.

PIPE_BUF is a different limit. POSIX guarantees atomic writes up to the implementation’s PIPE_BUF value, which is at least 512 bytes. On Linux it is 4096 bytes. If several processes write to the same pipe or FIFO, writes no larger than PIPE_BUF are not interleaved with one another. With O_NONBLOCK, that write either fits in full or fails with EAGAIN. Larger writes can interleave. Atomicity applies to each write() call, not to what a read() returns: one read can contain part of a write or bytes from several writes. Use framing in your protocol if the reader needs to reconstruct messages. Where available, query the FIFO’s _PC_PIPE_BUF value with fpathconf().

When all write descriptors are closed, the reader first drains any buffered bytes and then read() returns 0 to signal EOF. The FIFO pathname may remain on disk, but its buffered bytes do not persist after the channel is closed.

Named Pipes (FIFO)

A FIFO is created with mkfifo():

#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "usage: %s FIFO_PATH\n", argv[0]);
        return 2;
    }

    if (mkfifo(argv[1], 0600) == -1) {
        perror("mkfifo");  // Fails if the path already exists.
        return 1;
    }

    printf("Created FIFO: %s\n", argv[1]);
    return 0;
}

Once created, a FIFO appears in the filesystem and can be opened with open() just like a regular file. However, the open() call has special semantics for FIFOs:

  • open() for reading blocks until another process opens the same FIFO for writing
  • open() for writing blocks until another process opens the same FIFO for reading
  • You can pass O_RDWR to open both ends without blocking (but this is rarely the right approach)

The blocking behavior is part of the connection handshake. Coordinate startup or use the defined nonblocking behavior when either side must start independently. O_RDWR on a FIFO is Linux-specific in practice and undefined by POSIX.

Implementation details vary

The buffer layout, allocation strategy, and available tuning controls are kernel implementation details. Linux exposes capacity through F_GETPIPE_SZ and, on supported kernels, pipe information in /proc/<pid>/fdinfo/<fd>. Those interfaces are not portable, and their presence alone does not diagnose a slow consumer. Start by checking whether the reader keeps up and whether writes are blocking. Linux also provides splice() and vmsplice() for specific descriptor transfers; they are Linux-specific tools, not part of the basic pipe model.

Production Failure Scenarios

Broken Pipe Signal (SIGPIPE)

When every read end of a pipe or FIFO is closed, a write generates SIGPIPE. Its default action terminates the writer. If the process ignores, blocks, or catches the signal, write() fails with EPIPE. MSG_NOSIGNAL applies to socket send() calls, not to write() on a pipe.

Try the two-process case in Bash. head exits after one line; the producer then writes to a pipe with no reader and commonly exits from SIGPIPE (status 141 in Bash with pipefail):

set -o pipefail
yes | head -n 1
status=$?
printf 'pipeline status: %s (the producer may have received SIGPIPE)\n' "$status"

In a program that should keep running, ignore or handle SIGPIPE and check for EPIPE:

#include <signal.h>
#include <unistd.h>

signal(SIGPIPE, SIG_IGN);
/* write(pipe_fd, data, len) can now return -1 with errno == EPIPE. */

FIFO Deadlock Due to Blocking Open

In blocking mode, a read-only FIFO open waits for a writer, and a write-only open waits for a reader. That is a rendezvous, not inherently a deadlock: it completes when the peer opens the other end. A deadlock occurs if the program’s control flow prevents that peer from starting.

For a small two-process exercise, create a private temporary FIFO, start the reader, then write two newline-delimited records. The FIFO entry and its temporary data are removed when the script exits:

set -eu
demo_dir=$(mktemp -d)
trap 'rm -rf "$demo_dir"' EXIT
fifo="$demo_dir/demo"
mkfifo "$fifo"

cat "$fifo" &
reader_pid=$!
printf 'first\nsecond\n' > "$fifo"
wait "$reader_pid"

The writer’s open pairs with the reader’s open. After the writer closes, cat drains the remaining bytes and then sees EOF.

Forgetting to Close Unused Pipe Ends

In the fork pattern, if you forget to close the unused end of the pipe, the reading side may never see end-of-file because there is still a writer descriptor open (even if the original writer process does not actually write). This leads to the reader blocking forever on read().

Mitigation: Be disciplined about closing both ends immediately after fork() before any data operations begin. Use a wrapper function or clearly comment which side closes which end.

When fork() duplicates the file descriptor table, both processes hold references to the same pipe. The reader gets EOF only after every write end is closed and buffered bytes have been drained. If the child keeps an unused write descriptor open, the reader can block after the parent closes its copy because the kernel still sees a writer. The pipe object is released after the final descriptor closes.

This mistake is insidious because it produces no error at compile time, runtime, or even during initial testing. A process that forks, does not close the unused end, and then immediately writes to and reads from the pipe may work fine. Problems surface only under load or with specific timing, when the reader has been running longer than expected and the buffer fills up. Run lsof -p <pid> to check: if the reader process has both ends of the pipe open, that is your problem. The reader is in state S (interruptible sleep) on a read() that never returns.

The fix is mechanical. Immediately after fork(), before any data operations, each process should close the end it does not use. The parent closes pipefd[0] (read end) and the child closes pipefd[1] (write end). Automating this in a wrapper function prevents the error from creeping back in during maintenance:

void spawn_reader(int pipefd[2]) {
    pid_t pid = fork();
    if (pid == 0) {
        close(pipefd[1]);  // Always close write end first in child
        // Now use pipefd[0] for reading
    }
}

A common variant is closing the wrong end — parent closes write end, child closes read end — which swaps the direction. Data flows the wrong way and neither side sees what it expects. Comment each close explicitly and test with a simple pipe program before integrating into a larger pipeline.

Pipe Capacity Exhaustion

If a fast producer writes to a pipe faster than a slow consumer reads from it, the buffer fills up and the producer blocks. In a pipeline, this can cause the entire pipeline to stall — a slow consumer causes the producer to block, which causes the pipeline to back up.

Mitigation: On Linux, fcntl(F_SETPIPE_SZ) can request a larger capacity. You can also use nonblocking I/O with an event loop such as poll() or select(); epoll() is Linux-specific.

The buffer is finite, and its capacity depends on the operating system and kernel. Linux lets programs query pipe capacity with F_GETPIPE_SZ and, subject to system limits, change it with F_SETPIPE_SZ. A full blocking pipe makes the writer wait until the reader drains data. Raising capacity can delay backpressure, but it does not fix a consumer that cannot keep up.

What makes this tricky in practice is that the bottleneck may not be obvious. A pipeline like producer | processor | consumer stalls when the middle processor blocks on writing to its output pipe because the consumer is reading slowly. producer then blocks on writing to processor, and so on. The chain backs up from the slowest consumer. top or ps shows all pipeline stages in state S (sleeping), which can look like a deadlock but is actually a throughput mismatch.

Linux exposes some pipe details in /proc/<pid>/fdinfo/<fd>, but that interface is not portable. If a workload needs durable buffering, use a regular file or a message queue explicitly configured for persistence; neither a pipe nor a FIFO stores its stream on disk.

For real-time data pipelines, build backpressure awareness into the design. Use non-blocking I/O on all stages and an event loop that monitors both the input side and the output side. When the output pipe is full, the event loop stops reading from the input and waits. This naturally throttles the pipeline without any stage blocking indefinitely.

FIFO Permissions and Security

FIFOs created with mkfifo() respect the umask of the creating process. If you create a FIFO that is world-readable/writable, any user on the system can read or write to it. This is a security concern in multi-user environments.

Mitigation: Set appropriate permissions (e.g., mkfifo(path, 0660) for a group-owned FIFO), use filesystem ACLs, or place FIFOs in directories with restricted access.

Trade-off Table

Feature Anonymous Pipe Named Pipe (FIFO) Unix Domain Socket
Creation pipe() system call mkfifo() system call socketpair() or socket() + bind()
Filesystem Presence None (kernel-only) Yes (pathname remains until unlinked; it stores no stream data) None (kernel-only) or filesystem path for named sockets
Process Relationship Processes receive the descriptors, often through fork() Any process with access to the FIFO path Any process with access to the socket endpoint
Bidirectional No (POSIX pipes are unidirectional) No (POSIX FIFO semantics) Yes (full-duplex)
Capacity Finite; varies by OS and kernel Finite kernel buffer; varies by OS and kernel Depends on socket type and system
Message Boundaries None (byte stream) None (byte stream) None (byte stream for SOCK_STREAM) / Yes (for SOCK_DGRAM)
Persistence Stream ends when descriptors close FIFO name persists until unlinked; bytes do not Socket endpoint behavior depends on type and whether it has a path
Multiple Readers/Writers Supported but complex Supported but complex Supported natively
Typical Use Case Shell pipelines, parent-child streaming Daemon communication, cross-process coordination Network IPC, full-duplex local communication

Implementation Snippet(s)

C: Fork-based Anonymous Pipe

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
    int pipefd[2];
    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(1);
    }

    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(1);
    }

    if (pid == 0) {
        // Child: read from pipe
        close(pipefd[1]);  // Close write end
        char buf[256];
        size_t used = 0;
        while (used < sizeof(buf) - 1) {
            ssize_t n = read(pipefd[0], buf + used, sizeof(buf) - 1 - used);
            if (n < 0) {
                perror("read");
                close(pipefd[0]);
                return 1;
            }
            if (n == 0) {
                break;
            }
            used += (size_t)n;
        }
        buf[used] = '\0';
        printf("Child received: %s\n", buf);
        close(pipefd[0]);
        return 0;
    } else {
        // Parent: write to pipe
        close(pipefd[0]);  // Close read end
        const char *msg = "Hello from parent!";
        if (write(pipefd[1], msg, strlen(msg)) == -1) {
            perror("write");
            close(pipefd[1]);
            wait(NULL);
            return 1;
        }
        close(pipefd[1]);
        wait(NULL);  // Wait for child to finish
    }

    return 0;
}

Bash: Anonymous Pipe in Shell

#!/bin/bash
printf 'first\nsecond\n' | while IFS= read -r line; do
    printf 'reader got: %s\n' "$line"
done

For a FIFO open handshake and EOF exercise, use the isolated two-process example in the FIFO failure section.

Observability Checklist

  • Process state: Check if processes are blocked on pipe read/write using ps aux or lsof -p <pid>
  • File descriptors: Monitor open file descriptors for pipes with ls -la /proc/<pid>/fd/
  • Pipe capacity: On Linux, query capacity with fcntl(fd, F_GETPIPE_SZ); this interface is not portable.
  • SIGPIPE handling: On Linux, inspect SigIgn and SigCgt in /proc/<pid>/status; SigPnd shows pending signals, not the handler disposition.
  • FIFO existence: Check if FIFOs exist in expected locations with ls -la /tmp/*.fifo or similar
  • strace: Use strace -e trace=pipe,mkfifo,read,write -p <pid> to trace pipe operations
  • dtrace/SystemTap: Trace pipe create/open/read/write events across the system

Common Pitfalls / Anti-Patterns

Permissions & Security: FIFOs respect the standard Unix permission model. Ensure the FIFO is created with appropriate access controls — world-readable FIFOs allow any local user to participate in the communication channel. Use mode 0660 or 0664 with a specific group when possible. Unlike sockets, FIFOs are filesystem objects and their content can be inspected with ls. If you are communicating sensitive data, ensure the FIFO resides in a protected directory (e.g., /var/run/myapp/) with restricted permissions.

Denial of Service: A malicious process could open a FIFO for reading or writing and never close it, causing the legitimate counterpart to block on open(). Use non-blocking open (O_NONBLOCK) and implement timeouts for all I/O operations.

No Authentication: Pipes and FIFOs provide no built-in authentication. Any process that can reach the pipe (by file descriptor inheritance or by path) can read or write data. Implement your own application-layer authentication if needed.

Audit Trail: Pipe operations do not generate filesystem audit events by default (since FIFOs are not regular files). Monitor process-level audit logs for access patterns.

  1. Forgetting to close unused pipe ends — causes readers to hang forever waiting for EOF that never comes because a write end is still open somewhere.

  2. Assuming read returns the same write unit — write() of 100 bytes does not guarantee read() of 100 bytes. It may return 50, then another 50, or 1 byte at a time. Always handle partial reads.

  3. Ignoring SIGPIPE — writing to a pipe with no readers terminates the process by default. If the program ignores or handles it, check for EPIPE from write().

  4. Blocking on FIFO open without a counterpart — opening a FIFO in blocking mode hangs if no other process has the other end open. Use non-blocking mode or coordinate startup order.

  5. Using pipes for message-oriented data — pipes are byte streams with no message boundaries. If you send discrete messages, you need to frame them yourself (length prefix, delimiter, etc.).

  6. Not checking for errors — pipe(), mkfifo(), read(), and write() can all fail. Always check return values.

  7. Leaving FIFOs in filesystem after crash — if a process creating a FIFO terminates abruptly, the FIFO may remain. Implement cleanup on startup or use a process ID in the filename.

Quick Recap Checklist

  • POSIX pipes and FIFOs are unidirectional byte streams with no message boundaries; add framing in the application when needed
  • Anonymous pipes (pipe()) require shared descriptors, commonly through fork(); named pipes (mkfifo()) work between processes that can access the FIFO path
  • Always close the unused end of a pipe in both parent and child after fork() to avoid hangs
  • A write with no reader generates SIGPIPE; if ignored or handled, write() fails with EPIPE
  • Blocking FIFO opens wait for the other end; O_NONBLOCK has different read and write behavior
  • PIPE_BUF protects small writes from interleaving across writers; it does not create read-side message boundaries
  • Pipe capacity varies by OS and kernel; a full blocking pipe applies backpressure to the writer
  • A FIFO name remains until unlinked, but its bytes live only in the kernel buffer
  • Named pipes enable unrelated processes to communicate but lack built-in authentication

Interview Questions

1. How does the `pipe()` system call work internally in the kernel?

pipe() returns two file descriptors that refer to the read and write ends of a kernel-managed byte stream. The buffer layout and capacity are operating-system and kernel details; portable code should not depend on a fixed size. The channel has no filesystem pathname and no message boundaries.

2. What happens when you write to a pipe whose read end has been closed?

When all file descriptors referring to the read end of a pipe are closed, and a process attempts to write() to the pipe, the kernel sends a SIGPIPE signal to the writing process. By default, this signal terminates the process. If the process has blocked or ignored SIGPIPE, the write() call fails with errno set to EPIPE. This mechanism prevents a process from filling a pipe with data that no one will ever read.

3. What is the difference between anonymous pipes and named pipes (FIFOs)?

Anonymous pipes are created with pipe(); programs commonly pass the descriptors to related processes through fork(). FIFOs are created with mkfifo() and can be opened by any process with access to the path. The FIFO name remains until unlinked, but its bytes are buffered in the kernel and are not persistent. POSIX pipes and FIFOs are unidirectional byte streams with no message boundaries.

4. How can you avoid deadlocks when opening a FIFO?

In blocking mode, a read-only open waits for a writer and a write-only open waits for a reader. With O_NONBLOCK, read-only open succeeds without a writer, while write-only open fails with ENXIO until a reader is present. To coordinate the connection:

  • Non-blocking mode: Handle the initial read result and retry a write open after ENXIO, or use another readiness/coordination mechanism.
  • Coordinate startup order: Always start the reader first, or create the FIFO in a directory accessible to both processes before either starts.
  • O_RDWR: Linux permits opening a FIFO this way, but POSIX leaves the behavior undefined. Keeping a write end open can also prevent readers from seeing EOF.
5. Why do pipes have a limited capacity and what determines it on Linux?

Pipes have finite capacity, and the value varies by operating system and kernel. Linux exposes F_GETPIPE_SZ and F_SETPIPE_SZ to query and adjust capacity, subject to system limits. A full blocking pipe makes the writer wait for a reader to drain data; this backpressure slows a producer that is running ahead of its consumer.

6. How does the kernel implement pipe capacity and what happens when it is exceeded?

Buffer layout and capacity are implementation details. On Linux, F_GETPIPE_SZ reports capacity and F_SETPIPE_SZ can request a change subject to system limits. Those values and controls are not portable.

A full blocking pipe makes a writer wait; with O_NONBLOCK, a write may return a partial count or EAGAIN. If every read end is closed, a subsequent write generates SIGPIPE; if that signal is ignored or handled, write() fails with EPIPE.

7. What is the difference between pipe() and socketpair() for creating bidirectional communication channels?

On POSIX, pipe() creates a unidirectional pipe with two file descriptors: fd[0] for reading and fd[1] for writing.

socketpair() creates a pair of connected Unix domain sockets, which are bidirectional. Both file descriptors can send and receive. socketpair(AF_UNIX, SOCK_STREAM, 0, array) creates a connected stream socket pair (similar to a bidirectional pipe). SOCK_DGRAM creates a datagram socket pair with message boundaries. For bidirectional IPC between related processes, socketpair() is preferred over two pipes (one for each direction) because it uses fewer file descriptors and is semantically cleaner.

8. How does poll()/select() work with pipes and what are the key timeout considerations?

poll(), select(), and epoll() monitor file descriptors for I/O readiness. For the read end of a pipe, the descriptor is readable when data is present in the buffer or when the write end is closed (EOF). For the write end, it is writable when the buffer has space. These APIs let a single thread multiplex multiple pipes efficiently — blocking until at least one descriptor is ready.

Key considerations: poll() requires an array of pollfd structs; select() uses fd_sets with a maximum limit (FD_SETSIZE, often 1024); epoll() scales to many file descriptors without O(N) scanning on each call. For timeout, poll() takes an absolute or relative timeout depending on implementation; select() takes a struct timeval (seconds + microseconds). Always initialize the timeout structure — leaving it uninitialized is a common bug that causes unpredictable behavior.

9. Can a FIFO be opened for both reading and writing simultaneously and what is the purpose?

Linux permits opening a FIFO with O_RDWR, but POSIX leaves this behavior undefined. A process using this mode may keep a write end open and prevent readers from seeing EOF. Do not use O_RDWR as a portable way to wait for another process; use a defined open protocol or a socketpair() for bidirectional communication.

10. How does mkfifo interact with the filesystem and what permissions does it set by default?

mkfifo() creates a FIFO as a special file in the filesystem, similar to how mknod() creates device files. It respects the calling process's umask — if umask is 022, the FIFO gets mode 0666 & ~022 = 0644 (rw-r--r--). For a specific mode, pass the mode explicitly: mkfifo(path, 0666) sets rw-rw-rw- (subject to umask).

The FIFO appears in the filesystem like a regular file and persists until explicitly removed with unlink(). It can be inspected with ls -la and has an inode. Unlike anonymous pipes, FIFOs survive the creating process's termination. The filesystem metadata (location, permissions) is persistent; the FIFO's kernel buffer is destroyed when all processes close their file descriptors.

11. What is the semantics of closing the write end of a pipe when multiple readers exist?

After every write descriptor is closed, a reader first receives any bytes already buffered. Once those bytes are drained, read() returns 0 to signal EOF. A FIFO pathname can remain in the filesystem, but the stream data does not persist after the channel closes.

If only some write ends are closed (but not all), readers can still read remaining data and writers can still write. Only when all write ends are closed does EOF occur. This allows a pattern where multiple processes share the write end through inheritance, but each explicitly closes it when done — EOF occurs only when every writer has closed.

12. How does the kernel handle partial reads and writes on pipes?

A read() on a pipe returns whatever data is available, up to the buffer size requested — it may return fewer bytes than requested. This is distinct from message-oriented primitives where the read size is fixed. The pipe is a byte-stream with no message boundaries. A write() can similarly be partially completed — the return value indicates how many bytes were actually written.

For non-blocking I/O with O_NONBLOCK: if the pipe buffer has space, write() succeeds with all bytes; if the buffer is nearly full, it may write a partial amount. You must handle partial writes in your protocol by looping until all data is written, and handle partial reads by accumulating data until a complete message is formed. This byte-stream semantics is why pipes need protocol-level framing for discrete messages.

13. What is the maximum number of file descriptors for pipes and what limits them?

Each pipe uses two file descriptors, and each descriptor is subject to the process's RLIMIT_NOFILE. The operating system also sets resource limits for pipe buffers; the relevant controls differ across systems. On Linux, /proc/sys/fs/pipe-max-size limits the size of an individual pipe that an unprivileged process may request, not the number of pipes. Check the target system's documentation before tuning limits.

14. How do pipes interact with the fork() system call in terms of file descriptor inheritance?

When a process calls fork(), the child's file descriptor table is initialized as a copy of the parent's — all file descriptors (including pipe ends) are duplicated. Both parent and child then have both read and write ends of the pipe open. This is almost always wrong — the standard pattern requires each process to close the end it doesn't need. Failure to close the unused end leads to the reader never seeing EOF (because there is still an open write descriptor somewhere in the process tree).

File descriptors are preserved across exec() as well — if a process replaces itself with another program using execve(), the pipe file descriptors remain open. This allows pipelines like fork() → dup2() to connect stdin/stdout. The close-on-exec flag (FD_CLOEXEC) can be set with fcntl() to automatically close file descriptors on exec(), which is useful for pipe ends that should not leak into executed child programs.

15. What is the relationship between pipes and standard I/O (stdio) buffering?

When you fwrite() to a pipe via a FILE* stream, stdio buffers the data in userspace before calling write() at the kernel level. This buffering can cause surprising behavior in IPC: a fwrite() of 1 byte might result in a write() of 1 byte, but the data may sit in the buffer until fflush() is called or the buffer fills. Conversely, read() from a pipe with stdio may return data from the buffer rather than directly from the kernel.

For pipes connected to processes that expect immediate delivery (e.g., a server expecting newline-delimited messages), buffering can introduce latency. Use setbuf(fp, NULL) or setvbuf(fp, NULL, _IONBF, 0) to disable buffering on the pipe FILE* stream. For debugging, fflush() after each logical message ensures data is sent immediately.

16. How does tee() work and when would you use it for piping data between processes?

tee() reads data from one pipe and writes it to another pipe, while also allowing the data to be read by a third party. It duplicates data — one copy goes to the output pipe, another is left in the original pipe for subsequent reading. This is useful for splitting a data stream: one process writes to a pipe, another reads from it, and a third reads the same data simultaneously from the tee point.

The classic use case is the shell tee command: command | tee file.txt | another_command — tee writes command's output to file.txt and also passes it to another_command. In C, tee(input_fd, output_fd, buffer, flags) atomically copies data from input to output while leaving the data in the input pipe for a third consumer.

17. Can you use a pipe to communicate between a daemon process and its child processes?

Yes. A common pattern is for a parent (daemon) to create pipes before forking, then the child inherits the pipe ends. The parent closes the child's end of the child's read side (and vice versa), creating a unidirectional channel. For bidirectional communication, use two pipes (one for each direction) or a socketpair().

For a daemon and independently started processes, a FIFO lets each side connect through a shared filesystem path. An anonymous pipe requires the processes to receive its descriptors, commonly through inheritance after fork().

18. How does splice() improve performance compared to using pipes for data transfer?

splice() moves data between a file descriptor and a pipe buffer without copying data between kernel and user space. It uses the kernel's internal pipe buffer mechanism as a temporary holding area and redirects the data pointers without memcpy. For transferring data between files, sockets, or other descriptors, splice() can be significantly faster than a read()/write() loop because it avoids userspace entirely.

vmsplice() is related — it copies data from userspace to a pipe buffer, useful for sending data from a buffer you already have in memory. Both are used in high-performance networking and file I/O paths. For general IPC, classic pipes are simpler and the overhead is negligible unless you are moving very large amounts of data at very high rates.

19. What are the semantics of pipe ends and file descriptor close-on-exec flags after fork?

The close-on-exec flag (FD_CLOEXEC) is copied to the child during fork() — the child's file descriptor table entry has the same FD_CLOEXEC setting as the parent. This means that if you set FD_CLOEXEC on a pipe end before forking, the pipe end will be automatically closed when the child calls exec(). This is useful when you fork a helper process that should not inherit IPC file descriptors.

To set close-on-exec: fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC). To unset (keep across exec): clear the flag. If you want a pipe to survive an exec (e.g., stdin/stdout of the executed process), ensure FD_CLOEXEC is not set and use dup2() to remap the pipe end to the standard stream number before calling exec.

20. How does the kernel handle very large writes to pipes that exceed the pipe buffer size?

When a write() exceeds the pipe buffer capacity, the kernel handles it in stages: it fills the buffer with as much data as will fit, blocks the writer, and as the reader drains data, the writer is woken to continue writing the remainder. For non-blocking I/O, the write returns the number of bytes written before blocking would have occurred.

PIPE_BUF, not the total pipe capacity or /proc/sys/fs/pipe-max-size, sets the multiple-writer atomicity limit. POSIX guarantees that writes no larger than the implementation's PIPE_BUF are not interleaved with other writers' writes. POSIX requires at least 512 bytes; Linux uses 4096 bytes. Larger writes may be interleaved. Even an atomic write is only atomic at the writer: reads can split or combine data, so applications still need message framing.

Further Reading

Conclusion

Pipes and FIFOs are small byte-stream channels. Anonymous pipes are commonly inherited by child processes; FIFOs let unrelated processes connect through a path. Neither keeps message boundaries, and a FIFO path does not make its data durable. If the reader falls behind, the finite kernel buffer pushes back on writers.

For bidirectional or network communication, use a socket. For message boundaries or durable delivery, choose an IPC or messaging mechanism that provides those semantics. Pipes remain useful when a producer and consumer need a simple stream on one host.

For related IPC patterns, compare pipes with Unix domain sockets and message queues. select(), poll(), and (on Linux) epoll() can wait on multiple file descriptors.

Category

Related Posts

ASLR & Stack Protection

Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.

#operating-systems #aslr-stack-protection #computer-science

Assembly Language Basics: Writing Code the CPU Understands

Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.

#operating-systems #assembly-language-basics #computer-science

Boolean Logic & Gates

Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.

#operating-systems #boolean-logic-gates #computer-science