What this code should do is: there are parent.cpp and child.cpp. Parent will send whatever is in the buffer to child and child will send back whatever received to parent. I do not know what I am doing wrong. I am confused what is missing in the parent and what else I should include into the child. Thanks.
//parent.cpp
//Check for fork error
if ( (pid = fork()) < 0 )
{
cerr << "FORK ERROR" << endl;
return -3;
}
else if (pid == 0) // Child
{
close(fd1[1]);//Close parent's stdout-write
close(fd2[0]);//Close child's stdin-read
if (fd1[0] != STDIN_FILENO)//Make sure file desc. matches
{
if (dup2(fd1[0], STDIN_FILENO) != STDIN_FILENO)
{
cerr << "dup2 error to stdin" << endl;
}
close(fd1[0]);
}
if (fd2[1] != STDOUT_FILENO)//Make sure file desc. mathces
{
if (dup2(fd2[1], STDOUT_FILENO) != STDOUT_FILENO)
{
cerr << "dup2 error to stdout" << endl;
}
close(fd2[1]);
}
if ( execl("./child", "child", (char *)0) < 0 )
{
cerr << "system error" << endl;
return -4;
}
return 0;
}//end of child
else //parent
{
int rv;
close(fd1[0]);//Close parent's read
close(fd2[1]);//close child's write
if ( write(fd1[1], buffer, strlen(buffer)) != strlen(buffer))
{
cerr << "Write ERROR FROM PIPE" << endl;
}
if ( (rv = read(fd2[0], buffer, MAXLINE)) < 0 )
{
cerr << "READ ERROR FROM PIPE" << endl;
}
else if (rv == 0)
{
cerr << "Child Closed Pipe" << endl;
return 0;
}
cout << "Output of child is: " << buffer;
return 0;
}//end of parent
//child.cpp
char line[1000];
int MAXLEN=1001;
read(STDIN_FILENO, line, MAXLEN);