Program solution in C:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<errno.h>
#include<string.h>
#include<sys/wait.h>
int main()
{
int pipefd[2];
pid_t ret;
char readbuff[45];
char writebuff[45];
int byte;
int fdout;
int i;
int status;
pipe(pipefd);
/************************* creates pipe with pipefd[0] as read end and
pipefd[1] as write end***************************************/
ret = fork();
if(ret < 0)
{
perror(“can’t create a process”);
}
if(0 == ret) /****** child **********/
{
close(pipefd[0]); /********* close the read end of the pipe ************/
for(i=0 ; i<5 ; i++)
{
printf(“plz enter the string\n”);
memset(writebuff,”,45);
fgets(writebuff,44,stdin);
/* byte = read(0,writebuff,44);
if(-1 == byte)
{
printf(“can’t read\n”);
perror(“can’t read\n”);
}
*/
byte = write(pipefd[1],writebuff,(strlen(writebuff)+1));
if(-1 == byte)
{
printf(“can’t write”);
perror(“cannot write”);
}
} /*End of for loop*/
printf(“i m in child process\n”);
close(pipefd[1]);
exit(0);
}
else /******** PARENT ***********/
{
close(pipefd[1]);
wait(&status);
fdout = open(“outfile”,O_WRONLY|O_CREAT|O_TRUNC,S_IRWXU);
if(0> fdout)
{
printf(“file for writing is not created\n”);
perror(“write file error”);
}
for (i=0 ; i<5 ; i++)
{
while( (byte = read(pipefd[0],readbuff,45)) >0)
{
write(fdout,readbuff,byte);
}
}
close(pipefd[0]);
close(fdout);
return 0;
}
}
Leave a comment
Comments 0