Thursday, 26 September 2013

FIFO in UNIX


Here Server And Clint Will Create A Fifo Using mkfifo System Call And Will communicate . In Pipe Only parent and Child Can communicate but here any two process from same system can communicate

1. server fifo
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/types.h>
#include<string.h>

char serverbuf[1000];
char clintbuf[1000];
int main()
{
int a,fds,fdc,n;
if((a=mkfifo("/home/gaurav/cn/servertext.txt",0666))<0)
printf("\n fifo error");
if((a=mkfifo("/home/gaurav/cn/clinttext.txt",0666))<0)
printf("\n fifo error");
fds=open("/home/gaurav/cn/servertext.txt",O_RDWR);
fdc=open("/home/gaurav/cn/clinttext.txt",O_RDWR);
printf("\n welcome to  server process");
while(1)
{

printf("\n server::\t");
gets(clintbuf);
write(fdc,clintbuf,strlen(clintbuf));

printf("\n clint::\t");
n=read(fds,serverbuf,1000);
write(1,serverbuf,n);
}
close(fds);
close(fdc);

return 0;
}




2. Client Fifo
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>

char serverbuf[1000];
char clintbuf[1000];


int main()
{

int fds,fdc,n;
fds=open("servertext.txt",O_RDWR);
fdc=open("clinttext.txt",O_RDWR);
printf("\n welcome to clint process");
while(1)
{printf("\n server::\t");
n=read(fdc,clintbuf,1000);
write(1,clintbuf,n);
printf("\n clint::\t");
gets(serverbuf);
write(fds,serverbuf,strlen(serverbuf));
}
close(fds);
close(fdc);
return 0;
}


Pipe in Unix


Parent and Child Process can communicate with each other using pipe. Pipe is created using pipe system call.
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
char childbuf[200];
char parentbuf[200];

int main()
{int fdp[2],fdc[2],n;
pid_t pid;

if(pipe(fdp)<0)
printf("\n parent pipe error");
if(pipe(fdc)<0)
printf("\n child pipe error");
if((pid=fork())==0)
{
printf("\n welcome to child process");
close(fdp[1]);
close(fdc[0]);
while(1)
{printf("\n message from parent");
n=read(fdp[0],childbuf,200);
write(1,childbuf,n);
printf("\n message to parent");
gets(parentbuf);
write(fdc[1],parentbuf,strlen(parentbuf));
}}
else
{close(fdp[0]);
close(fdc[1]);
printf("\n welcome to parent process");
while(1)
{
printf("\n message to child");
gets(childbuf);
write(fdp[1],childbuf,strlen(childbuf));
printf("\n message from child");
n=read(fdc[0],parentbuf,200);
write(1,parentbuf,n);
}
} 
waitpid(pid,NULL,0);
return 0;
}