2

I have a srand(time(NULL)) at the beginning of the execution, then I am doing

*pos_x = (rand() % HEIGHT);
*pos_y = (rand() % WIDTH);

to generate random numbers.

This works fine when I run my program manually, but when I lunch my program with this script :

#!/bin/bash

i="0"
team_number="0"

while [ $i -lt 30 ]
do
  ./lemipc `pwd` team_number
i=$[$i+1]
  if (( $i % 10 == 0 ))
  then
    team_number=$[$team_number+1]
fi
echo "create process $i"
usleep 10000
done

I always get the same numbers for all the processes.

I even tried to add a usleep to fix this but it still doesn't work. I get this for exemple :

97 51 
create process 1
97 51 
create process 2
97 51 
create process 3
97 51 

where 97 is pos_x and 51 pos_y.

Have an idea why ?

Dimitri Danilov
  • 1,338
  • 1
  • 17
  • 45
  • 1
    Probably, your program executes too fast, thus causing `time` to return the same value each time? `time` returns the number of seconds elapsed since the start of the UNIX era, so if your script makes it all into less than a second, there's a large chance, it'll be the same value. – ach Mar 23 '16 at 14:13
  • 2
    Can you post a [mcve] - the minimum program code necessary to reproduce the issue? – Angew is no longer proud of SO Mar 23 '16 at 14:14
  • Why not output the value 'time(NULL)'? Maybe the same value is output for all processes, you know, for the same seed, srand always generate same number sequence. – Alanmars Mar 23 '16 at 14:15

2 Answers2

7

The time() call has only whole-second precision. If your programs all run the same second, they will all use the same seed.

You must add more entropy. Consider using the return value of getpid() if you have it, or else investigate the platform's random sources.

unwind
  • 391,730
  • 64
  • 469
  • 606
2

This is cause usleep is delaying the execution of the next script the amount of microseconds (10000 = 0.01 seconds). time(NULL) returns SECONDS, thus making each time(NULL) returning value the same. Increase the amount of time it's delayed

Mr. E
  • 2,070
  • 11
  • 23