Reputation: 1371
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.
Upvotes: 0
Views: 452
Reputation: 1689
This is what is happening in your code:
The parent forks. i is still 0, so readerChild() is called by that child. The parent AND the child continue to the second iteration of the loop. They BOTH fork again. Thus you get 2 writer children. 1 of them is a child and one is a grandchild.
At the end of your child section, you need to prevent it from looping. put a break;
Upvotes: 1
Reputation: 1656
Personally I'd just write one function per child... unless readerChild()/writerChild() blocks the thread and exits, the readerChild will spawn a new writerChild since it will still be executing within the context of that loop.
Upvotes: 0
Reputation: 272517
Remember that when you fork()
, both parent and child start up in identical states (other than the return value of fork()
). So the child will also execute your outer for
loop, and spawn its own child (see diagram below). You need to alter your control flow to take account of that.
P --> fork --> fork --> wait
| --> writerChild -- wait
|
--> readerChild --> fork --> wait
--> writerChild --> wait
Upvotes: 2