Search code examples
clinuxnamed-pipesfifo

Is there a way to open FIFO(named pipe) in write-only way without blocked


I use FIFO in my server. Due to some limitations, I have to open the FIFO in write-only firstly, then I use fork to create another process to open FIFO in read-only. But I find that, it will be blocked when I open the FIFO in write-only firstly, thus the server can not continue to run to fork.

For some reason I can not open FIFO in read-only firstly, Is there a way to open FIFO in write-only without blocked? I have tried open("/tmp/ngfifo", O_WRONLY | O_NONBLOCK) but will return error

The small example is like this :

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>

int main()
{
    int pipe_fd = open("/tmp/ngfifo", O_WRONLY);  // It will be blocked here, is there a way to open without block.
    if(pipe_fd < 0) {
        fprintf(stderr, "Opened fifo failed %d\n", errno);
        return -1;
    }
    printf("wait..\n");

    if (fork() > 0) {
        printf("begin to write \n");
    } else {
        int read_fd = open("/tmp/ngfifo", O_RDONLY);
        // ...
        printf("begin to read \n");
    }
    return 0;
}

Solution

  • From the Linux FIFO man page:

    Under Linux, opening a FIFO for read and write will succeed both in blocking and nonblocking mode. POSIX leaves this behavior undefined. This can be used to open a FIFO for writing while there are no readers available.

    So on Linux, it is possible for the writing process to call open("/tmp/ngfifo", O_RDWR | O_NONBLOCK) to open the write end of the pipe without blocking because it is also open for reading. However, this is not portable to other operating systems.