Reputation: 150
I have composed the 2 following programs, in one I continuously write a string to a buffer and pass it through the FIFO to the other one, which reads what I've passed.
/*write*/
int main()
{
int i=0, fd1;
char buffer[16];
mkfifo("fifo1", 0666);
fd1 = open("fifo1", O_WRONLY);
for(;;)
{
sprintf(buffer, "string%d", i);
write(fd1, buffer, 16);
i++;
}
}
/*read*/
int main()
{
int i=0, fd1;
char buffer[16];
fd1 = open("fifo1", O_RDONLY);
for(;;)
{
sleep(1);
read(fd1, buffer, 16);
printf("%s\n", buffer);
}
}
So,I wanted to analyze the behaviour between these two programs. I opened 2 terminals. In the first one I ran the write program first and in the second one I ran the read program. After seeing the read program printing some of the strings, I stopped the execution of the write program(through keyboard), to examine what happens. The read program, even though I had stopped the write program, kept printing strings.
Can someone explain to me the behaviour of these two programs? What exactly happens?
(I didn't bother writing function checking)
Upvotes: 0
Views: 828
Reputation: 21
When you launch both the program the "read" and "write" end of a FIFO is opened, as you do the message transaction by writing and reading it works fine, read gets blocked until some program writes to it.
as soon as you terminate the writing program you have closed one end of FIFO and the connection broke. so Now "read" will every time read EOF and return 0, you will end up in non-blocking of read case. In your case you are not clearing buffer so the Old value will be printed.
you can open and close connections for every Message so even if you close the "write" process abruptly, the next open call of the "read" process will get blocked until some process opens "write" end.
Note: I have ignored API error return types here.
/*write*/
int main()
{
int i=0, fd1;
char buffer[16];
mkfifo("fifo1", 0666);
for(;;)
{
fd1 = open("fifo1", O_WRONLY);
sprintf(buffer, "string%d", i);
write(fd1, buffer, 16);
i++;
close(fd1);
}
}
/*read*/
int main()
{
int i=0, fd1;
char buffer[16];
fd1 = open("fifo1", O_RDONLY);
for(;;)
{
fd1 = open("fifo1", O_RDONLY);
sleep(1);
read(fd1, buffer, 16);
printf("%s\n", buffer);
close(fd1);
}
}
Upvotes: 2