Using the O_nonblock mode affects read and write calls to the FIFO.
A read call to an empty, blocked FIFO (that is, not opened with the O_nonblock flag) waits until the data is readable to continue execution. In contrast, a read call to an empty, non-blocking FIFO will immediately return 0 bytes.
A write call to a fully blocked FIFO will wait until the data can be written to continue execution. For a non-blocking FIFO, if the FIFO cannot receive all of the written data, it will be executed according to the following rules.
- If the requested data length is less than or equal to Pipe_buf bytes, the call fails and the data cannot be written.
- If the length of the requested data is greater than pipe_buf bytes, part of the data is written, the number of bytes written to the FIFO is returned, and the return value may be 0.
The length of the FIFO is a very important factor to consider. The system has a limit on the length of data that can exist in a FIFO at any one time. It is defined by the #define PIPE_BUF statement, which can usually be found in the header file limits.h. In Linux and many other Unix-like systems, its value is typically 4096 bytes, but in some systems it may be as small as 512 bytes. The system specifies that in a FIFO opened in o_wronly mode (that is, blocking mode), if the length of the written data is less than or equal to pipe_buf, either all bytes are written, or none of the bytes are written.
Although this limitation is not very important for simple cases where there is only one FIFO write process and one FIFO read process, it is common to apply only one FIFO and allow multiple different programs to send requests to a FIFO read process. If several different programs try to write data to the FIFO at the same time, it is critical to ensure that data blocks from different programs do not want to be interleaved. This means that each write operation must be "atomized".
If you can ensure that all write requests are destined for a blocking FIFO, and that the data length of each write request is less than or equal to Pipe_buf bytes, the system ensures that the data is never interleaved. It is often a good idea to limit the length of data passed through the FIFO to pipe_buf bytes, unless only one write process and one read process are used.
Read and write operations for named pipe--fifo