I have been trying to use fork and pipe to enable two communication between a parent process and 2 child processes.This code works perfectly when I use one child process, but if I use two, I am not getting sent between the parent and child process #2. It simply prints the first two messages again.This is the code that I have been using:
#include<iostream>
#include<stdlib.h>
#include<signal.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>
using namespace std;
char String1[] = "Hello, this is the message from parent to child1";
char String2[] = "Hello, this is the message from child1 to parent";
char String3[] ="Hello this is a msg from parent to child2";
char String4[]="Hello this is a msg from child2 to parent";
void catchInt(int signum)
{
cout<<"Child1's PID is "<<(int)getpid()<<"\n";
cout<<"Child1 process terminated"<<"\n";
cout<<"Waiting for child2 to complete"<<"\n";;
exit(1);
}
void catchInt1(int signum)
{
cout<<"Child2's PID is "<<(int)getpid()<<"\n";
cout<<"Child2 process terminated\n";
exit(1);
}
int main ()
{
char buf[1024];
int fds1[2], fds2[2],fds3[2],fds4[2];
int child1r, child1w, parentr1, parentw1,child2r,child2w,parentr2,parentw2;
pipe (fds1);
pipe (fds2);
pipe (fds3);
pipe (fds4);
child1r = fds1[0];
child1w = fds2[1];
parentr1 = fds2[0];
parentw1 = fds1[1];
child2r=fds3[0];
child2w=fds4[1];
parentr2=fds4[0];
parentw2=fds3[1];
pid_t pid = fork();
pid_t pid1=fork();
if (pid>0)
{
close (child1r); close (child1w);close (parentr2);close (parentw2);close(child2r);close(child2w);
write (parentw1, String1,sizeof (String1));
read (parentr1, buf, sizeof (String2));
cout<<" Parent:"<<buf<<"\n";
sleep(1);
kill(pid, SIGINT);
wait(NULL);
}
else if(pid==0)
{
close (parentr1); close (parentw1);close (parentr2);close(parentw2);close(child2r);close(child2w);
write (child1w, String2, sizeof (String2));
read (child1r, buf, sizeof (String1));
cout<<" Child1:"<<buf<<"\n";
signal(SIGINT, catchInt);
pause();
exit(1);
}
if (pid1>0)
{
close (child1r); close (child1w);close (parentr1);close (parentw1);close(child2r);close(child2w);
write (parentw2, String1, sizeof (String3));
read (parentr2, buf, sizeof (String4));
cout<<" Parent:"<<buf<<"\n";
sleep(1);
kill(pid1, SIGINT);
wait(NULL);
cout<<"Parent PID :"<<(int)getpid()<<"\n";
cout<<"Parent process terminated"<<"\n";
}
else if (pid1==0)
{
close (parentr1); close (parentw1);close (parentr2);close(parentw2);close(child1r);close(child1w);
write (child2w, String2, sizeof (String4));
read (child2r,buf,sizeof (String3));
cout<<" Child2:"<<buf<<"\n";;
signal(SIGINT, catchInt1);
pause();
}
return 0;
}