INTERPROCESS COMMUNICATION USING
PIPES
PIPES
#include “ sys/types.h “
#include “ sys/ipc.h “
#include “ errno.h “
#include “ fcntl.h “
#include “ stdio.h “
#include “ sys/stat.h “
#include “ unistd.h “
#include “ string.h “
#define MAXLINE 50
void client(int,int);
void server(int,int);
int main(void)
{
int pipe1[2],pipe2[2];
pid_t childpid;
pipe(pipe1);
pipe(pipe2);
if((childpid=fork())==0)
{
close(pipe1[1]);
close(pipe2[0]);
server(pipe1[0],pipe2[1]);
exit(0);
}
close(pipe1[0]);
close(pipe2[1]);
client(pipe2[0],pipe1[1]);
waitpid(childpid,NULL,0);
exit(0);
}
void client(int readfd,int writefd)
{
size_t len;
size_t n;
char buf[MAXLINE];
printf("\nEnter Filename:");
fgets(buf,MAXLINE,stdin);
len=strlen(buf);
if(buf[len-1]=='\n')
len--;
write(writefd,buf,len);
while((n=read(readfd,buf,MAXLINE)) “ 0)
write(STDOUT_FILENO,buf,n);
}
void server(int readfd,int writefd)
{
int fd;
size_t n;
char buf[MAXLINE+1];
if((n=read(readfd,buf,MAXLINE))==0)
buf[n]='\0';
if((fd=open(buf,O_RDONLY)) “ 0)
{
snprintf(buf+n,sizeof(buf)-n,"Can't open %s :",strerror(errno));
n=strlen(buf);
write(writefd,buf,n);
}
else
{
while((n=read(fd,buf,MAXLINE)) “ 0)
write(writefd,buf,n);
printf("%s",buf);
close(fd);
}
}
OUTPUT
[user1@localhost user1]$ cc pipe.c
[user1@localhost user1]$ ./a.out
Enter Filename:pipes.c
#include “ stdio.h “
main()
{
printf("\nWELCOME\n");
}
[user1@localhost user1]$
No comments:
Post a Comment