FIFO
- C course
- Advanced
- Lesson 32/83
- 5 min
Learn named pipes with FIFO.
What is a FIFO?
A FIFO (named pipe) is a special file with a path in the filesystem. As the name suggests, it carries data in First-In First-Out order. It is created with mkfifo(path, mode); requires the <sys/stat.h> and <sys/types.h> headers.
Anonymous pipes only work between related processes; a FIFO is open to any two processes because it is found via its path. It is opened with open and used with read and write. open for reading blocks until a writer opens; so the fork pattern is convenient for tests.
The open and fork pattern
You open the FIFO for reading with open(path, O_RDONLY) and for writing with open(path, O_WRONLY). The call blocks until both sides have called open; this automatic pairing is ideal for tests.
With fork the child can be the reader, the parent the writer. The parent writes with write(fd, "fifo", 4), the child reads with read(fd, buf, 4). When done, close(fd) and finally unlink(path) removes the FIFO file. wait(NULL) reaps the child.
Practice Transfer data via FIFO
Set up the FIFO with unlink("/tmp/cb_fifo"); mkfifo("/tmp/cb_fifo", 0644);. Fork a child with pid_t pid = fork();. In the child: int fd = open("/tmp/cb_fifo", O_RDONLY);, char buf[16]; memset(buf, 0, sizeof(buf));, read(fd, buf, 4);, printf("%s\n", buf);, close(fd); _exit(0);. In the parent: int fd = open("/tmp/cb_fifo", O_WRONLY);, write(fd, "fifo", 4);, close(fd);, wait(NULL);, unlink("/tmp/cb_fifo");.
Starter code
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
// Set up FIFO
// Fork a child to read
// Parent writes and waits
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(void) {
unlink("/tmp/cb_fifo");
mkfifo("/tmp/cb_fifo", 0644);
pid_t pid = fork();
if (pid == 0) {
int fd = open("/tmp/cb_fifo", O_RDONLY);
char buf[16];
memset(buf, 0, sizeof(buf));
read(fd, buf, 4);
printf("%s\n", buf);
close(fd);
_exit(0);
}
int fd = open("/tmp/cb_fifo", O_WRONLY);
write(fd, "fifo", 4);
close(fd);
wait(NULL);
unlink("/tmp/cb_fifo");
return 0;
}Expected output
fifo
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match FIFO parts
| Term | Meaning |
|---|---|
mkfifo |
Creates FIFO |
open |
Opens FIFO |
read |
Reads data |
unlink |
Removes FIFO |
2 What is the second parameter of mkfifo?
- Byte count
- Process id
- File descriptor
- Access permissions Correct answer
Explanation: The second parameter is mode, the access permissions (e.g. 0644).
3 mkfifo call
mkfifo("/tmp/cb_fifo", ____);
mkfifo("/tmp/cb_fifo", 0644);
Explanation: 0644 gives read-write permissions.