0

I have two processes p0, p1 running in parallel. I'm using named pipe IPC where reader (p0) writes to the pipe and reader (p1) reads from it. Here, the reader starts before writer. The reader has to loop till the writer writes to the pipe and the data is available to read.

In writer.c

int fd;
char * myfifo = "/tmp/myfifo";
char string1[20] = "Hello";
mkfifo(myfifo, 0666);
fd = open(myfifo, O_WRONLY);
write(fd, string, sizeof(string1);
close(fd);

In reader.c , I use

# define MAX_BUF 20
int fd;
char buf[MAX_BUF];
while(1){
        fd = open(myfifo, O_RDONLY);
        read(fd, buf, MAX_BUF);
        printf("Received: %s\n", buf);
        if(strlen(buf) != 0){ // buf is not empty, so break from the loop
            break;
        }
        close(fd);
    }

When executing this code, the writer blocks. What am I missing here?

Thanks, K

marc
  • 949
  • 14
  • 33
  • `man 3 mkfifo` *Once you have created a FIFO special file in this way, any process can open it for reading or writing, in the same way as an ordinary file. However, it has to be open at both ends simulta‐ neously before you can proceed to do any input or output operations on it. Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa.* – EOF Sep 21 '17 at 22:50
  • 2
    Why are you looping in the reader? Either the open or the read is going to block, so there's really no need to loop. Where is the writer blocking? Is the `open` not returning, or is it the `write`? – William Pursell Sep 21 '17 at 23:18
  • 2
    Are you actually running this code with no error checking? If you run the reader first, I would expect the open to fail, and the read to fail, and you will get a tight loop printing "Received: ..." with a bunch of garbage. – William Pursell Sep 21 '17 at 23:22
  • Yes, The reader starts first, so it needs to wait till the writer writes into the pipe. – marc Sep 22 '17 at 13:37

0 Answers0