I've just started to learn Fifos in C and I've written the following program to test their funcionalities:
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
void error(){
printf("Error occured: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
int main (int argc, char* argv[]){
const char fifoName[] = "test";
unlink(fifoName);
if(mkfifo(fifoName, 0700) < 0)
error();
pid_t pid ;
if((pid=fork()) < 0)
error();
if (pid == 0){
FILE *f = fopen(fifoName, "r");
puts("\nchild started writing\n");
for(size_t i = 0; i < 10 ; i++){
fputc(i + 48, f);
fputc(i+48, stdout);
}
puts("\nchild finished writing\n");
fclose(f);
}
else{
FILE *f = fopen(fifoName, "w");
puts("parent started reading");
while(!feof(f)){
char c = fgetc(f);
if(c != EOF)
putc(c, stdout);
}
puts("parent finised reading");
fclose(f);
}
unlink(fifoName);
return 0;
}
The problem is that the parent process (the reader) doesn't terminate, on the contrary, it keeps reading EOF chars even after the child has finished writing correctly. As you can see I decided to use FILE* streams, opening them in read and write mode depending on the process. By doing so I have the standard functions fprintf, fscanf etc and overall I have the buffered-derived performance of the streams. Could this implementation be the reason behind the problematic behaviour?