A named pipe (also known as a FIFO for its behavior) is an extension to the traditional pipe concept on Unix and Unix-like systems, and is one of the methods of inter-process communication (IPC)
Instead of a conventional, unnamed, shell pipeline, a named pipeline makes use of the filesystem .
In this example i have used "mknod" , for creating the file and two separate processes (fifo_server & fifo_client ) can access the pipe by name — one process can open it as a reader, and the other as a writer.
############ Server ##############
#include<stdio.h>
#include<stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#define FIFO_FILE "my_file.txt"
void main()
{
FILE *fp ;
char read_buffer[100];
umask(0);
/*mknod - create a special or ordinary file
* The file type must be one of S_IFREG, S_IFCHR, S_IFBLK, S_IFIFO, or
* S_IFSOCK to specify a regular file */
mknod(FIFO_FILE,S_IFIFO|0777,0);
while(1)
{
fp=fopen(FIFO_FILE,"r");
fgets(read_buffer,sizeof(read_buffer),fp);
printf("received value is %s \n",read_buffer);
fclose(fp);
}
}
Instead of a conventional, unnamed, shell pipeline, a named pipeline makes use of the filesystem .
In this example i have used "mknod" , for creating the file and two separate processes (fifo_server & fifo_client ) can access the pipe by name — one process can open it as a reader, and the other as a writer.
############ Server ##############
#include<stdio.h>
#include<stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#define FIFO_FILE "my_file.txt"
void main()
{
FILE *fp ;
char read_buffer[100];
umask(0);
/*mknod - create a special or ordinary file
* The file type must be one of S_IFREG, S_IFCHR, S_IFBLK, S_IFIFO, or
* S_IFSOCK to specify a regular file */
mknod(FIFO_FILE,S_IFIFO|0777,0);
while(1)
{
fp=fopen(FIFO_FILE,"r");
fgets(read_buffer,sizeof(read_buffer),fp);
printf("received value is %s \n",read_buffer);
fclose(fp);
}
}
############### Client ##################
#include<stdio.h>
#include<stdlib.h>
#define FIFO_FILE "my_file.txt"
void main()
{
FILE *fp ;
char write_buffer[100] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
while(1)
{
fp=fopen(FIFO_FILE,"w");
fputs(write_buffer,fp);
fclose(fp);
}
}
Output ..
At the server side we see the data coming in from the FIFO !! Simple isn't it ??
received value is ABCDEFGHIJKLMNOPQRSTUVWXYZ
received value is ABCDEFGHIJKLMNOPQRSTUVWXYZ
received value is ABCDEFGHIJKLMNOPQRSTUVWXYZ
received value is ABCDEFGHIJKLMNOPQRSTUVWXYZ
received value is ABCDEFGHIJKLMNOPQRSTUVWXYZ
--Cheers !!
No comments:
Post a Comment