I'm writing a little Linux fifo test program.
I created a pipe using mkfifo mpipe
. The program should perform one write per argument sent to it. If no arguments are sent, then it performs one read from the pipe.
Here is my code
int main(int argc, char *argv[])
{
if (argc > 1)
{
int fd = open("./mpipe", O_WRONLY);
int i = 1;
for (i; i < argc; i++)
{
int bytes = write(fd, argv[i], strlen(argv[i]) + 1);
if (bytes <= 0)
{
printf("ERROR: write\n");
close(fd);
return 1;
}
printf("Wrote %d bytes: %s\n", bytes, argv[i]);
}
close(fd);
return 0;
}
/* Else perform one read */
char buf[64];
int bytes = 0;
int fd = open("./mpipe", O_RDONLY);
bytes = read(fd, buf, 64);
if (bytes <= 0)
{
printf("ERROR: read\n");
close(fd);
return 1;
}
else
{
printf("Read %d bytes: %s\n", bytes, buf);
}
close(fd);
return 0;
}
I would expect the behavior to be something like this...
I call ./pt hello i am the deepest guy
, and I would expect it to block for 6 reads. Instead one read seems enough to trigger multiple writes. My output looks like
# Term 1 - writer
$: ./pt hello i am the deepest guy # this call blocks until a read, but then cascades.
Just wrote hello
Just wrote i
Just wrote am
Just wrote the # output ends here
# Term 2 - reader
$: ./pt
Read 6 bytes: hello
Could someone help explain this weird behavior? I thought that every read would have to match with a write with regards to pipe communication.