15.5. FIFOsFIFOs are sometimes called named pipes. Pipes can be used only between related processes when a common ancestor has created the pipe. (An exception to this is mounted STREAMS-based pipes, which we discuss in Section 17.2.2.) With FIFOs, however, unrelated processes can exchange data.We saw in Chapter 4 that a FIFO is a type of file. One of the encodings of the st_mode member of the stat structure (Section 4.2) indicates that a file is a FIFO. We can test for this with the S_ISFIFO macro.Creating a FIFO is similar to creating a file. Indeed, the pathname for a FIFO exists in the file system.
As with a pipe, if we write to a FIFO that no process has open for reading, the signal SIGPIPE is generated. When the last writer for a FIFO closes the FIFO, an end of file is generated for the reader of the FIFO.It is common to have multiple writers for a given FIFO. This means that we have to worry about atomic writes if we don't want the writes from multiple processes to be interleaved. (We'll see a way around this problem in Section 17.2.2.) As with pipes, the constant PIPE_BUF specifies the maximum amount of data that can be written atomically to a FIFO.There are two uses for FIFOs. ExampleUsing FIFOs to Duplicate Output StreamsFIFOs can be used to duplicate an output stream in a series of shell commands. This prevents writing the data to an intermediate disk file (similar to using pipes to avoid intermediate disk files). But whereas pipes can be used only for linear connections between processes, a FIFO has a name, so it can be used for nonlinear connections.Consider a procedure that needs to process a filtered input stream twice. Figure 15.20 shows this arrangement.With a FIFO and the UNIX program tee(1), we can accomplish this procedure without using a temporary file. (The tee program copies its standard input to both its standard output and to the file named on its command line.)mkfifo fifo1 prog3 < fifo1 & prog1 < infile | tee fifo1 | prog2 We create the FIFO and then start prog3 in the background, reading from the FIFO. We then start prog1 and use tee to send its input to both the FIFO and prog2. Figure 15.21 shows the process arrangement. Figure 15.20. Procedure that processes a filtered input stream twice![]() Figure 15.21. Using a FIFO and tee to send a stream to two different processes[View full size image] ![]() ExampleClientServer Communication Using a FIFOAnother use for FIFOs is to send data between a client and a server. If we have a server that is contacted by numerous clients, each client can write its request to a well-known FIFO that the server creates. (By "well-known" we mean that the pathname of the FIFO is known to all the clients that need to contact the server.) Section 17.2.2.With the arrangement shown in Exercise 15.10.) Figure 15.22. Clients sending requests to a server using a FIFO![]() Figure 15.23. Clientserver communication using FIFOs![]() |