简体   繁体   中英

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
  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 ie 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"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM