Reputation: 13
I am trying to understand piping in C. I have constructed two test programs that should be working but while running ,the second one prints uninitialized chars rather than the expected string. Is there anything obvious I am missing?
int main()
{
int parentToChild[2]; //1 Write
int childToParent[2]; //0 Read
pipe(parentToChild);
pipe(childToParent);
int parent = fork();
if(!parent)
{
close(parentToChild[1]);
close(childToParent[0]);
dup2(1,childToParent[1]); //sets child's stdout to send to parent
dup2(0,parentToChild[0]); //sets child's stdin to come from parent
execl("./program","./program",NULL);
}
close(childToParent[1]);
close(parentToChild[0]);
FILE* readin = fdopen(childToParent[0],"r");
FILE* writeto = fdopen(parentToChild[1],"w");
fprintf(writeto,"msg\n");
fflush(writeto);
return 0;
}
int main()
{ //The child process
fprintf(stderr,"Program started\n");
char buff[1024];
fgets(buff,1024,stdin);
fprintf(stderr,"%s",buff);
}
Upvotes: 0
Views: 294
Reputation: 17345
The issue is in the lines:
dup2(1,childToParent[1]); // Error!
dup2(0,parentToChild[0]); // Error!
The order of the file descriptors in the dup2 call is switched. To fix you code you have to change these lines by:
dup2(childToParent[1],1); //sets child's stdout to send to parent
dup2(parentToChild[0],0); //sets child's stdin to come from parent
The dup2(new_fd, old_fd) makes the newe fd to be a copy of the old fd argument. For more info just check the man page of the dup2.
Note: I tested your code by introducing the changes above and now it's working correctly.
Upvotes: 1