In addition to what Jonathan Leffler said, I want to say that you should add checks to make sure that when read
fails, you deal with the condition gracefully.
if (pid > 0) { /* parent process */
int parentVal = 0;
close(mypipefd[READ]); // The parent is not going to read from the first pipe.
// Close the read end of the pipe.
close(mypipefd2[WRITE]); // The parent is not going to write to the second pipe.
// Close the write end of the pipe.
while(1) {
parentVal++;
write(mypipefd[WRITE],&parentVal,sizeof(parentVal));
printf("Parent: writes value : %d\n", parentVal);
// If the chld closes the write end of the second pipe,
// break out of the loop.
if ( read(mypipefd2[READ],&parentVal,sizeof(parentVal)) > 0 )
{
printf("Parent: reads value : %d\n", parentVal);
}
else
{
break;
}
}
close(mypipefd[WRITE]); // Close the write end of the first pipe
close(mypipefd2[READ]); // Close the read end of the second pipe
}
else { /* child process */
int childVal = 0;
close(mypipefd[WRITE]); // The child is not going to write to the first pipe.
// Close the write end of the pipe.
close(mypipefd2[READ]); // The child is not going to read from the second pipe.
// Close the read end of the pipe.
while(1) {
// If the parent closes the write end of the first pipe,
// break out of the loop.
if ( read(mypipefd[READ],&childVal,sizeof(childVal)) > 0 )
{
printf("child: read value : %d\n", childVal);
}
else
{
break;
}
childVal++;
write(mypipefd2[WRITE],&childVal,sizeof(childVal));
printf("child: write value : %d\n",childVal);
}
close(mypipefd[READ]); // Close the read end of the first pipe
close(mypipefd2[WRITE]); // Close the write end of the second pipe
}