Search code examples
csystems-programmingmkfifo

C can't read from fifo (named pipe)


I create a fifo, but i can't read from it. What's the problem? Here is a code and output. If I use O_RDONLY without O_NONBLOCK program just wait.

pid_t p;
int fd;
char str[]="sample";

mkfifo("myfifo", S_IRUSR | S_IWUSR);

fd = open("myfifo", O_RDWR);

printf("write %d byte\n", write(fd, str, 5));

close(fd);

fd = open("myfifo", O_RDONLY | O_NONBLOCK);

printf("read %d byte\n",read(fd, str, 6));

close(fd);

unlink("myfifo");

Output:

write 5 byte
read 0 byte

Solution

    1. Issue is your closing the file,

    you can try this or fork another process and read the file, which is mostly why named fifos are used for i.e inter-process communication

    This link explains in detail How to send a simple string between two programs using pipes?

    pid_t p;
    int fd;
    char str[]="sample";
    
    mkfifo("myfifo", S_IRUSR | S_IWUSR);
    
    fd = open("myfifo", O_RDWR);
    
    printf("write %d byte\n", write(fd, str, 5));
    
    printf("read %d byte\n",read(fd, str, 6));
    
    close(fd);
    
    unlink("myfifo");