Communication between programs/processes: how can we create and access FIFOs (named pipes) in Linux?

Written by Ian on 26/08/09


The following code creates a named pipe if it does not yet exist, and then starts to read from it.


#include
#include
#include
#include
int main(void)
{
FILE *fp;
char buf[20];
/* Create the FIFO if not existing */
umask(0);
mknod("mypipe", S_IFIFO|0666, 0);
while(1)
{
fp = fopen("mypipe", "r");
fgets(buf, 20, fp);
printf("We received: %s\\n", buf);
fclose(fp);
}
return(0);
}


And the following code will write to the same named pipe (the thing is writes is the command line argument you give when you execute the code).


#include
#include
int main(int argc, char *argv[])
{
FILE *fp;
if((fp = fopen("mypipe", "w")) == NULL) {
fprintf(stderr,"fopen gave an error\\n");
exit(1);
}
fputs(argv[1], fp);
fclose(fp);
return(0);
}


On a Linux PC, you can compile these like this:

gcc -o fifo_read fifo_read.c -static

gcc -o fifo_write fifo_write.c -static


Then you can execute them in two terminal windows like this:

In window 1: ./fifo_read

In window 2: ./fifo_write "this is an experiment"


Ctrl-C exits either of them.


Now the thing to wonder, is whether it matters which way round they are launched. If you try to execute the fifo_write program first instead, do they behave the same?

The answer to this question illustrates blocking behaviour! This we explored in a previous article.