Burak Özmen
Burak Özmen

Reputation: 873

making children processes wait for another for loop

i've been making google searches about my question for 2 days but im done with it. I have very basic information about process management, fork etc. I've been told to create some children processes of a same parent process and send them seeds by using pipes so they can produce some random numbers, all for their own. But I'm stuck at creating children processes.

for (i = 0; i < NUM_PLAYERS; i++) {
    /* TODO: spawn the processes that simulate the players */
    switch(pid = fork()){
        case -1:  // ERROR
            exit(EXIT_FAILURE);

        case 0:  // CHILD PROCESS
            printf("My parent id is %d \n", getppid());
            exit(EXIT_SUCCESS);

        default: // PARENT PROCESS
            wait(NULL);
    }
}

When I go with this code, parent creates NUM_PLAYERS children but I can't seem to use them in another for loop since they had terminated at the end of the case 0. When I just remove exit(EXIT_SUCCESS); line, so many processes are created and they have all different parents. So my question is, how to properly create children processes and use them later?

Upvotes: 0

Views: 1528

Answers (2)

Duck
Duck

Reputation: 27552

void do_something()
{
    //create random numbers or whatnot
}

//...........

case 0:  // CHILD PROCESS
    printf("My parent id is %d \n", getppid());
    do_something();
    exit(EXIT_SUCCESS);

You'll need the parent to wait on the children in a later loop. The way you have it will block until a single child returns. You want to create multiple children before then waiting on them.

Note that you still have to add the pipe logic so parent/child can communicate.

EDIT

This is the broad outline of what you need to do:

for (i = 0; i < NUM_PLAYERS; i++) {
    /* TODO: spawn the processes that simulate the players */
    switch(pid = fork()){
        case -1:  // ERROR
            exit(EXIT_FAILURE);

        case 0:  // CHILD PROCESS
            printf("My parent id is %d \n", getppid());
            exit(EXIT_SUCCESS);
    }
}

// only the parent will ever execute below here

for (i = 0; i < NUM_PLAYERS; i++) 
{
    while ( /* read each child's pipe*/)
    {
        //do something with data
    }
}

for (i = 0; i < NUM_PLAYERS; i++) 
    wait(NULL);

return(0);

Upvotes: 2

abligh
abligh

Reputation: 25129

If you remove exit(EXIT_SUCCESS) your child will continue executing where it was forked, IE it will go back to the close brace of the for() loop, and generate new children itself. What do you want the child to do? You should make it do that, and then do exit(EXIT_SUCCESS) and not let it return to to the for() loop.

Note also that wait() will only wait for one process to quit.

Upvotes: 3

Related Questions