Originally Posted by
Elkvis
that looks ok. if you didn't replace stdin and stdout, you'd have to find a way to notify the child process that it should use some other file descriptor for each. using dup2 is just simpler. if you still want your parent process to have its own stdin/stdout, you could use something like fdopen() to create buffered C-style streams from those file descriptors. the boost libraries also have adapter classes to make istream/ostream objects from the descriptors, but that may be a discussion for another thread.
I changed it a bit into this:
Code:
int fd[2];
int fds[2];
pipe(fd);
pipe(fds);
int childpid = fork();
if(childpid == 0)
{
close(fd[1]);
close(fds[0]);
fd[0] = open("test1",O_RDONLY);
fds[1] = open("test2",O_WRONLY)
dup2(fd[0],0);
dup2(fds[1],1);//child writes to fds[1]
char wrd[128];
cin.getline(wrd,'\0');
cout<<wrd<<endl;
close(fd[0]);
close(fds[1]);
//exec child
}
else{
close(fd[0]);
close(fds[1]);
fd[1] = open("test1",O_WRONLY);
fds[0] = open("test2",O_RDONLY);
//parent writes to fd[1] instead of stdout
dup2(fd[1],1);
dup2(fds[0],0);
cout<<"aaaa.dddd.ffff.gggg"<<endl;
close(fd[1]);
close(fds[0]);
}
The problem is that although parent writes to test1 and the child tries to read from it(child's cout to test1 works,I've checked it)sometimes it reads the half line and sometimes nothing at all as child's cout is in test2 and only sometimes there's something written there and yet not the whole thing.What could be wrong?