c - Why does writing to a named pipe continue after no one is reading? -


i'm doing experiments learn named pipes. it's understanding os block program writes named pipe until program reads named pipe. i've written 2 programs, startloop , readbyte. startloop creates fifo , continually writes each read of client (readbyte):

#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h>  int main(int argc, char *argv[]) {     const char num = 123;     mkfifo("fifo", s_irusr | s_iwusr | s_irgrp | s_iwgrp);     int fd = open("fifo", o_wronly | o_creat | o_trunc, s_irusr | s_iwusr | s_irgrp | s_iroth);     while (1) {         printf("loop_start\n");         write(fd, &num, sizeof(num));     }     close(fd);     return 0; } 

readbyte reads 1 byte fifo when run:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h>  int main(int argc, char *argv[]) {     char num;     int fd;     if ((fd = open(argv[1], o_rdonly, s_irusr | s_iwusr | s_irgrp | s_iroth)) == -1) {         perror("cannot open input file\n"); exit(1);     }      read(fd, &num, sizeof(num));     printf("%d\n", num);     close(fd);     return 0; } 

readbyte prints number expected when run on "fifo":

hostname:dir username$ ./readbyte fifo  65 

as expect, loopstart doesn't print until read fifo readbyte. however, when becomes unblocked, writes "fifo" several times instead of being suspended. why this?

hostname:dir username$ ./startloop loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start loop_start 

"it's understanding os block program writes named pipe until program reads named pipe."

that understanding incorrect. write not block unless pipe/fifo full. pipe manul:

a pipe has limited capacity. if pipe full, write(2) block or fail, depending on whether o_nonblock flag set (see below).

as why first write appears block - doesn't. open blocks. fifo manaul:

the fifo must opened on both ends (reading , writing) before data can passed. normally, opening fifo blocks until other end opened also.

update: above true first write. there more explanation. once readbyte program closes fifo, subsequent write calls should start failing.


Comments

Popular posts from this blog

multithreading - Exception in Application constructor -

React Native allow user to reorder elements in a scrollview list -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -