How would you, cleanly, get a parent process to create multiple children, where each child has to do it’s own thing. Also the children have to communicate with the parent using unnamed pipes, so I don’t think execv can be used here.
I had something like this:
int main (int argc, const char * argv[])
{
pid_t pids[2];
int i;
for (i = 0; i < 2; ++i) {
if ((pids[i] = fork()) < 0) {
fprintf(stderr, "Error. Couldn't fork\n");
exit(EXIT_FAILURE);
} else if (pids[i] == 0) { // child
if (i == 0) {
readerChild();
} else {
writerChild();
}
}
}
//parent stuff;
for (i = 0; i < 2; ++i) {
wait(NULL);
}
return 0;
}
but according to my output, two writer children get created, when I only wanted one.
Remember that when you
fork(), both parent and child start up in identical states (other than the return value offork()). So the child will also execute your outerforloop, and spawn its own child (see diagram below). You need to alter your control flow to take account of that.