I think your shared use of the pipe in each child is causing you trouble. Also, the fork logic there is a little convoluted and harder to follow. Here is something that allows two children to spawn, write to their own pipes, and have the parent receive the messages. It is certainly not generalized for N children, for that you would need an altogether different setup.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * m1 = "Child #1";
const char * m2 = "Child #2";
int main () {
char mbuff[1024] = {0};
pid_t pid1 = 0, pid2 = 0;
int pipes1[2] = {0}, pipes2[2] = {0};
pipe(pipes1); /* for child 1 */
pid1 = fork ();
if (pid1 == 0) {
/* I am the [first] child */
write (pipes1[1], m1, strlen(m1));
close (pipes1[0]);
close (pipes1[1]);
fprintf (stderr, "First child wrote\n");
exit (0);
}
/* Parent continues here */
pipe(pipes2);
pid2 = fork ();
if (pid2 == 0) {
/* I am the [second] child */
write (pipes2[1], m2, strlen(m2));
close (pipes2[0]);
close (pipes2[1]);
fprintf (stderr, "Second child wrote\n");
exit (0);
}
/* Parent continues and reads all data */
read(pipes1[0], mbuff, 1024);
printf ("Parent reads: %s\n", mbuff);
close (pipes1[0]);
close (pipes1[1]);
read(pipes2[0], mbuff, 1024);
printf ("Parent reads: %s\n", mbuff);
close (pipes2[0]);
close (pipes2[1]);
return 0;
} L7Sqr
Practically a Master Poster
657 posts since Feb 2011
Reputation Points: 201
Solved Threads: 124