Anonymous pipes overcome the main problems with using files for inter-process communication. However, pipes have one drawback not shared by files they can only be used by processes that have a common ancestor which created the pipe for them and passed on its file descriptors to them.
FIFO files (also known as named pipes) solve even this problem, while still maintaining all the advantages of anonymous pipes. The way FIFO files solve the problem is that they have file names (i.e. directory links) and so can be open()ed and used by any processes, whether they are related or not, as long as they have appropriate access permissions to the file.
In order to create a FIFO file you can either use the command mknod from the shell prompt or you can use the mknod() system call from within one of your programs. Both the mknod command and the system call can be used to create more than just FIFO files. We'll see other uses of mknod when we look at writing device drivers.
Using the mknod command to create a FIFO file from the shell prompt is easy the command has the format:
$ mknod filenane p
This command will create a FIFO file called filename with access permissions 666 minus the current value of unask.
The mkmod() system call has the prototype:
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int mknod(char *pathnane, mode_t mode, dev_t dev);
Where pathname is the name of the file to be created, mode is a combination of the permission bits to be set on the file and a specification of the type of file to be created (S_IFIF0 in this case), and dev is a value which is used when creating device special files and so, for a FIFO, this has the value zero. For example:
#define MYMODE (S_IFIF0 | S_IRUSR | S_IWUSR) mknod{"myfifo", MYMODE, 0);
Once a FIFO file has been created it can be accessed using just the standard open() system call by any process with appropriate permissions. When open(), a FIFO file has the same basic functionality as an anonymous pipe, i.e. read()s block when the pipe is empty, write()s block when the pipe is full and setting the O_NONBLOCK flag with fcntl() will cause read() and write() to return immediately with an EAGAIN error in situations where they would otherwise have blocked.
Because they can be accessed simultaneously by many unrelated processes, FlFOs are useful in applications where there are multiple readers and/or multiple writers. In this situation there needs to be a rule to determine what happens if two writers try to write to the FIFO at the same time. The rule is that a write() of any number of bytes up to the size of the pipe (4096 bytes in Linux) is guaranteed to be atomic. This means that the data from multiple write() operations will not intermingle in the FIFO but will be maintained as separate messages. Exactly the same rule applies to anonymous pipes, but here it is less useful because they are less often used in these types of application.