Generating Random Number in Child Process using Fork

Hello All, I am stuck up in a program where the rand functions ends up giving all the same integers. Tried sleep, but the numbers turned out to be same... Can anyone help me out how to fix this issue ? I have called the srand once in the program, but I feel like when I call fork the child process again calls the srand.. any fix for that ?

This is my working code (just the rand function messing up)

int main (int argc, char *argv[])  
{ 
    
    int seed = time(0);
    sleep(10);
    srand(seed);    
    int i, nproc;
    nproc = atoi(argv[1]);
    pid_t child[nproc];
    
    int status;
    
    if (argc < 2)
    {
        fork(); // if no argument - only one child process is created
    }

    else
    {
        for(i = 0; i < nproc; i++) 
        {
            switch(pid = child = fork())
                {
                    case -1:
                    perror("fork-error");
                    exit(1);

                    case 0:
                    printf("id = %d : RND = %d",i, (int)(rand()% 100 +1)); //generating random number for each child
                    exit(i);

                    default:
                    waitpid(child, &status, 0); //wait for the child to terminate
                    printf("Exiting %d = %d\n", i, WEXITSTATUS(status));
                    break;

                }
            
        }
    }    
    return 0; 
}

Put the same random seed into your RNG, and you'll get the same numbers from it in the same order.

You call srand once, in the parent, then get the very first number generated from every child, which is naturally identical.

Try seeding after fork, with something like time()+getpid()

Did that by moving srand to every place, but same random integers.

If you put the same seed in, you get the same numbers out.

time() only changes once a second. How long does your program take to run? Less than a second?

That's why I suggested putting the PID into it as well. That changes every single time...

1 Like

less than a second... ok i'll try using PID too and will reply you soon

---------- Post updated at 01:00 PM ---------- Previous update was at 12:55 PM ----------

thanks Corona - this worked srand(time(0)+getpid()); but I had to call this within the case 0 i.e child process

Yes, you have to do it in the child process. If you do it in the parent, you get 20 identical copies of the parent, and 20 identical copies of the parent's seed, and 20 identical random numbers. I thought I mentioned that, but see I didn't. Sorry about that.

1 Like