
Recall first from Pipes, EOF and redirection
- An ordinary pipe carries ordered bytes, without preserving write boundaries.
- An empty pipe reaches EOF only after every writer reference disappears.
- dup2 changes a descriptor mapping; it does not copy file contents.
Launch two filters without waiting too early
3 min readThe first lesson on this topic connected two programs with one pipe and redirects. Now launch both stages of a pipeline before waiting and give unrelated processes a pathname rendezvous, answering how to avoid deadlock and how a FIFO reaches other processes.
For ls | wc -l, create one pipe and two children. The first child maps the write endpoint onto descriptor 1. The second maps the read endpoint onto descriptor 0. Each closes both original pipe descriptors after duplication.
The parent closes both endpoints and supervises; only the children move data.
This complete teaching program requires descriptors 0, 1, and 2 to be open, default signal behavior, and no competing child reaper.
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
static void collect(pid_t pid)
{
while (waitpid(pid, NULL, 0) == -1) {
if (errno != EINTR) {
perror("waitpid");
exit(EXIT_FAILURE);
}
}
}
static void run_filter(int p[2], int source, int target,
const char *program, char *const args[])
{
if (dup2(source, target) == -1) {
perror("dup2");
_exit(126);
}
(void)close(p[0]);
(void)close(p[1]);
execvp(program, args);
int saved = errno;
perror(program);
_exit(saved == ENOENT ? 127 : 126);
}
int main(void)
{
int p[2];
if (pipe(p) == -1) {
perror("pipe");
return EXIT_FAILURE;
}
pid_t producer = fork();
if (producer == -1) {
perror("fork");
(void)close(p[0]);
(void)close(p[1]);
return EXIT_FAILURE;
}
if (producer == 0) {
char *args[] = {"ls", NULL};
run_filter(p, p[1], STDOUT_FILENO, "ls", args);
}
pid_t consumer = fork();
int fork_error = errno;
if (consumer == 0) {
char *args[] = {"wc", "-l", NULL};
run_filter(p, p[0], STDIN_FILENO, "wc", args);
}
(void)close(p[0]);
(void)close(p[1]);
if (consumer == -1) {
errno = fork_error;
perror("fork");
(void)kill(producer, SIGKILL);
collect(producer);
return EXIT_FAILURE;
}
collect(producer);
collect(consumer);
return EXIT_SUCCESS;
}
Save it as two_filters.c. Compile with warnings, then compare its count with the shell pipeline in the same unchanged directory.
cc -std=c11 -Wall -Wextra -Wpedantic two_filters.c -o two_filters
./two_filters
ls | wc -l
This program reports launch failures, without shell exit-status rules. A shell retains every stage's status. Bash normally uses the last stage; pipefail changes that choice.
A leaked read endpoint in the producer prevents SIGPIPE when the consumer exits. An extra writer complicates EOF detection.
Going deeperDescriptors can collide with standard input and output
If a launcher starts with descriptor 0 or 1 closed, a new pipe can reuse that number. Blindly closing both originals after dup2() could then close the installed standard stream. Establish valid standard descriptors before allocating pipes, or move internal descriptors above 2 with F_DUPFD_CLOEXEC and handle equal-number duplication explicitly. A service can attach missing standard streams to /dev/null; an interactive shell should verify its terminal setup instead.
Cross-compile with your board's SDK, the toolchain and libraries prepared for that target. Run the binary on Linux; a host executable cannot test ARM behavior.
Give unrelated processes a FIFO name
4 min readA A FIFO, short for first in, first out, is a named pipe opened through a filesystem pathname. mkfifo() creates the name, not a running reader or writer. Its C interfaces are:
#include <sys/stat.h>
int mkfifo(const char *path, mode_t mode);
int mkfifoat(int dirfd, const char *path, mode_t mode);
For mkfifoat(), include <fcntl.h> and define _POSIX_C_SOURCE 200809L before headers. A relative path is resolved against the directory descriptor dirfd. An absolute path ignores it. Both functions return zero on success or minus one on failure. Creation permissions are reduced by umask.
1Observe the open handshake
Create a private directory in terminal A. Keep the printed pathname so you can use it in terminal B. mktemp -d chooses a fresh directory; verify command success before continuing.
labdir=$(mktemp -d /tmp/fifo-lab.XXXXXX) || exit 1
chmod 700 "$labdir"
mkfifo -m 600 "$labdir/events" || exit 1
printf '%s\n' "$labdir"
cat "$labdir/events"
cat waits while opening for reading. In terminal B, replace the example directory with the actual printed path and send one record.
printf 'temperature=24\n' > /tmp/fifo-lab.REPLACE/events
The two opens meet. cat receives the line, then exits after that writer closes and the buffer drains. Afterwards, remove your FIFO and directory with rm "$labdir/events" and rmdir "$labdir" in terminal A.
| Open request | Peer absent | Peer present |
|---|---|---|
| O_RDONLY | Waits for writer | Succeeds |
| O_WRONLY | Waits for reader | Succeeds |
| O_RDONLY with O_NONBLOCK | Succeeds | Succeeds |
| O_WRONLY with O_NONBLOCK | Fails with ENXIO | Succeeds |
A nonblocking read from an empty FIFO returns zero if there are no writers. It returns EAGAIN if a writer remains. A future writer can reconnect to an existing FIFO, so EOF need not end a long-running server's lifetime. Define whether the server closes and reopens, or intentionally holds a dummy writer. A dummy writer suppresses EOF and therefore changes disconnect detection.
Linux allows opening a FIFO with O_RDWR without a peer. POSIX does not define this behavior. It can hide peer disappearance or let a process read its own bytes; do not mistake it for a portable connection handshake. See fifo(7).
2Separate naming, framing, and replies
For a server, use one well-known request FIFO and a private reply FIFO per client. The client creates and opens its reply reader nonblocking before submitting a request. The server opens that reply FIFO for writing with O_NONBLOCK, so a vanished client cannot stall every other client.
A protocol defines how peers exchange and interpret data. Framing is an application rule that identifies where each record starts and ends within a byte stream. Define a request length, identifier, and validated reply name. Encode bytes explicitly: C structure padding and byte order can differ across boards.
Keep each complete request within PIPE_BUF and send it with one write(). The server accumulates read bytes and extracts whole records; one read can split a request or combine several. Reject oversized lengths before allocating memory. One server reader is simplest: multiple readers compete for bytes rather than each receiving a copy.
Bound client retries, reply sizes, and outstanding requests. Opening a reply FIFO may fail with ENXIO because the client disappeared. A later write can still fail with EPIPE. These are ordinary lifecycle failures, not permission failures.
Place production FIFOs in a service-owned directory under /run, commonly backed by tmpfs. tmpfs is a memory-backed filesystem whose data can use RAM and, when available, swap. The FIFO node's placement controls naming and permissions; FIFO payloads still use kernel pipe buffers. /run contents disappear across reboot, so recreate the directory and node at startup.
FIFOs also work on supported disk filesystems; ext4 is not a requirement. Some shared or Windows-backed mounts reject FIFO creation. Inspect the actual mount and error rather than recommending root access. On WSL, use the Linux filesystem for this lab. In a shared /tmp, never trust an existing predictable name after EEXIST. A private directory prevents unrelated users replacing that name.
Key takeaways
- Launch every pipeline stage before waiting, and close unused endpoints everywhere.
- FIFO open behavior depends on direction, peer presence, and O_NONBLOCK.
- A FIFO only names a rendezvous: queued bytes stay in kernel pipe buffers, so applications must add framing and per-client reply channels.
Reflect
- Explain to a colleague, in two sentences: connect child processes using fork, dup2, exec, and correct descriptor closure.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.