Home > Software design >  rand() generates same numbers when used with fork()
rand() generates same numbers when used with fork()

Time:11-12

I'm trying to generate random numbers in a specific range. I'm also using children processes in my program.

However, the rand() function generates the same number, say 550, in the for loop even though I have randomized it using srand()

Here is the code for demonstration:

int main()
{

int count = 5;
int i;
  for (i = 0; i < count; i  )
  {
    pid_t pid = fork();
    if (pid == 0)
    {

      // random number between 500 and 700
      srand(time(NULL));
      int random = rand() % 100   500;
      printf("%d\n", random);

      exit(0);
    }
    else
    {

      wait(NULL);
    }
  }

  return 0;
}

Where is the problem? How can I fix that?

Any help is appreciated.

CodePudding user response:

All of the processes your program is spawning are created very fast, so the value returned by the call time(NULL) is the same for all of them. It is passed as a seed to the pseudo random number generator, making it to produce the same sequence of pseudo-random numbers for each process.

In order to get different numbers in each process, you should make sure each process gets a unique seed value. Simplest way to achieve this would be to add the counter i to the time value:

srand(i   time(NULL));
  •  Tags:  
  • c
  • Related