Hello all,
Iam trying to write a program where parent forks a child.
parent will give a line of text to child and child will dup the stdin and stdout to the pipe fds.
and it will toggle the text. Now parent will read from the pipe and write to the stdout.
But here in my case it's getting blocked while reading from the pipe.
I could not able to trace out where the error is
If any body suggestions would be hightly appreciated.
Code:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define LINELENGTH 256
int main()
{
int pf[2],ps[2],cpid,n = 0;
char *line,*newLine;
line = malloc(LINELENGTH*sizeof(char));
newLine = malloc(LINELENGTH*sizeof(char));
memset(line,0,LINELENGTH);
memset(newLine,0,LINELENGTH);
if(pipe(pf) < 0 || pipe(ps))
printf("%s\n",strerror(errno));
if( (cpid = fork()) == 0)
{
close(pf[1]);
close(ps[0]);
if(pf[0] != STDIN_FILENO)
{
if(dup2(pf[0],STDIN_FILENO) < 0)
{
printf("c:%s\n",strerror(errno));
close(pf[0]);
}
}
if(ps[1] != STDOUT_FILENO)
{
if(dup2(ps[1],STDOUT_FILENO) < 0)
{
printf("c:%s\n",strerror(errno));
close(ps[1]);
}
}
execl("./toggelcase","toggelcase",(char*)0);
exit(0);
}
close(pf[0]);
close(ps[1]);
while((fgets(line,LINELENGTH,stdin)) != NULL)
{
if((write(pf[1],line,LINELENGTH)) < 0)
printf("p:%s\n",strerror(errno));
if((n = (read(ps[0],newLine,LINELENGTH))) < 0)
printf("p:%s\n",strerror(errno));
if(n == 0)
{
printf("Child closed the pipe\n");
break;
}
printf("newLine %s\n",newLine);
if(fputs(newLine,stdout) == EOF)
printf("%s\n",strerror(errno));
}
exit(0);
}