Hey guys. I'm working on a project where a parent process forks two children (so Process A is parent to both Process B and Process C). I need the children to write to the pipe so that the parent can see it. When I make a simple one child pipe to the parent, i got it working. But i'm hitting some snags here with two children. Currently, the parent reads nothing, as if the children never got to write to the pipe. I'm not amazing at pipes, so there very well could be a stupid mistake. Here's my code:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define MSGSIZE 37
char *msg1 = "Child process 1 is sending a message!";
char *msg2 = "Child process 2 is sending a message!";
main()
{
char inbuf[MSGSIZE];
int p[2];
pid_t pid[2];
pid[0]=fork();//Parent creates first child
if (pid[0]!=0) { //If pid[0]=0, then process is child and should not fork
pid[1]=fork(); //current process is parent, so fork a second child
}
if (pipe(p)==-1) { //error
perror("pipe call");
exit(1);
}
switch(pid[0]){
case -1:
printf("Fork failed");
exit(2);
break;
case 0: //first child is active. Write to pipe
close(p[0]);
write(p[1], msg1, MSGSIZE);
close(p[1]);
exit(EXIT_SUCCESS);
default://parent is active. Read pipe messages (2)
close(p[1]);
read(p[0], inbuf, MSGSIZE);
close(p[0]);
printf("%s\n", inbuf);
wait(NULL);
}
switch(pid[1]){
case -1:
printf("Fork failed");
exit(2);
break;
case 0: //first child is active. Write to pipe
close(p[0]);
write(p[1], msg2, MSGSIZE);
close(p[1]);
exit(EXIT_SUCCESS);
default://parent is active. Read pipe messages (2)
close(p[1]);
read(p[0], inbuf, MSGSIZE);
close(p[0]);
wait(NULL);
printf("%s\n", inbuf);
}
exit(0);
}
How can I get these child processes to write properly so that the parent can read them? Thanks for the help!