Question

I created a PIPE using the below code. But there is something wrong when the program runs fd = open(FIFO, O_RDONLY);. The phenomenon is blocking. Could someone give me some advice? Thanks a lot .

#include<errno.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#define FIFO "/tmp/test"

int main(int argc, char** argv)
{
    char buf_r[100];
    int fd;
    int nread;
    if((mkfifo(FIFO, O_CREAT) < 0) && (errno != EEXIST))
    {
            printf("can not create FIFO\n");
            exit(1);
    }

    printf("Prepare read data\n");
    fd = open(FIFO, O_RDONLY);
    if(fd == -1)
    {
            exit(1);
    }

    while(1)
    {
            if((nread = read(fd, buf_r, 100)) == -1)
            {
                    if(errno == EAGAIN) printf("No data\n");
            }

            if(buf_r[0]=='Q') break;

            buf_r[nread]=0;
            printf("data is:%s\n", buf_r);
            sleep(1);
    }

}
Was it helpful?

Solution

Opening a FIFO blocks until a "communication peer" is connected to the FIFO as well so that the pipe is successfully established.

BTW, when creating the FIFO fails, you should output (at most) a warning and continue - there are chances that the FIFO already exists and can be reused. And maybe /root/test/test is not the best place for this FIFO...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top