Named Pipes (FIFO) in Shell

Level 5207 keystrokes

mkfifo creates a named pipe: a special file through which one process writes and another reads. Opening it blocks until both a reader and a writer are present, so here the reader runs in the background (or the writer does) and the data passes straight through.

Shell code

# Create a named pipe (FIFO) in the filesystem
1mkfifo /tmp/myfifo
# Start a reader in the background; it waits until someone writes
2cat /tmp/myfifo &
# Write a line; cat receives it and prints it
3echo "Message through FIFO" > /tmp/myfifo
# Wait for the background cat to finish
4wait
# A FIFO is a file, so remove it when done
5rm /tmp/myfifo
# Second example: the writer runs in the background this time
6mkfifo /tmp/pipe
# A producer subshell writes one item per second into the pipe
7(for i in 1 2 3; do echo "Item $i"; sleep 1; done) > /tmp/pipe &
# The consumer prints items as they arrive and stops when the writer closes
8cat /tmp/pipe
9rm /tmp/pipe

Output

Message through FIFO
Item 1
Item 2
Item 3
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • /× 16
  • "× 4
  • ;× 3
  • &× 2
  • >× 2
  • (× 1
  • )× 1
  • $× 1

More Shell examples at level 5

← Shell typing practice