Usman Khan
Usman Khan

Reputation: 686

Forking N child processes properly

So I am programming a simple rummy card game. I need to create either 3, 4 or 5 processes where the parent acts as the dealer handing the cards to them. I am coming across an unexpected fault I am not sure how to approach.

The output I get is:

15019373x-apollo:/home/15019373x/comp2432/lab3$ ./rummy 3
Child: 1 PID 26581
Child: 2 PID 26582
Child: 3 PID 26585
15019373x-apollo:/home/15019373x/comp2432/lab3$ Child: 2 PID 26584
Child: 3 PID 26586
Child: 3 PID 26583
Child: 3 PID 26587

So I was trying to create 3 processes but the loop seems to create 7. I'm not too sure what's happening.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int players = atoi(argv[1]);
    char deck[52][3];
    int i, pid, cid;

    if (players > 5 || players < 3)
    {
            printf("%d is not the allowed number of players, min is 3 and max is 5\n", players);
            exit(1);
    }

    for (i = 0; i < argc - 2; i++)
    {
            strcpy(deck[i], argv[i+2]);
    }

    for (i = 0; i < players; i++)
    {
            pid = fork();
            if (pid < 0)
            {
                    printf("Fork Failed\n");
                    exit(1);
            }
            else if (pid == 0)
            {
                    printf("Child: %d PID %d\n", i+1, getpid());
            }
    }

}

If someone could point me in the right direction I'd be very grateful.

Thanks a lot!

Upvotes: 0

Views: 142

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

Remember that the children also continue executing the for loop and fork more children.

As a simple fix (as you are clearly still developing this program), call exit() after the printf in the child code. You don't want the children to keep executing code that is only intended for the parent to run.

Upvotes: 2

Related Questions