C
FIFO
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.
Exercise 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");.
Show example 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;
}
Test yourself
-
Match FIFO parts
- mkfifo
- Creates FIFO
- open
- Opens FIFO
- read
- Reads data
- unlink
- Removes FIFO
-
What is the second parameter of mkfifo?
- Byte count
- Process id
- File descriptor
- Access permissions
Show answer
Access permissions — The second parameter is mode, the access permissions (e.g. 0644).
-
mkfifo call
mkfifo("/tmp/cb_fifo", ____);
Show answer
mkfifo("/tmp/cb_fifo", 0644);
Next lesson: Shared memory