0

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
  • 1
    Pipes don't store messages. As soon as you close the file descriptor, the message you wrote to it is discarded. Pipes need consumers to be reading while producers are writing. – alvits Apr 06 '16 at 01:13

1 Answers1

0
  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"); 
Community
  • 1
  • 1
Dilip Kumar
  • 1,736
  • 11
  • 22