0

I would like to make a variable (that belongs to a process) get a new random value, each time the new process starts.

I need this random generation to make every process created sleep a random number of seconds. At the beginning of the program I used srand(time(NULL)), and in the function that the process would run I used

int sleeptime = rand() % 16 + 5; //that's because I need values from 5 to 20.

I've tried to implement such a thing, but I saw that for every process the value of the variable is the same.

I think that if I took as argument for srand(..) the current time in milliseconds (time at which the respective process begins) I would get the random values. The problem is I didn't find any information for this. The only thing suggested on different pages is the well known: srand(time(NULL));(where time(NULL) returns the current time in seconds).

Can you, please, suggest me some way to implement this? Thank you in advance.

wonderingdev
  • 1,132
  • 15
  • 28
  • 1
    Since all the processes start at the same time, they're probably all calling `srand` with the same time, and therefore getting the same random number(s) back from `rand`. You need a better source of randomization for `srand`. – Steve Summit Apr 25 '16 at 19:29
  • 1
    Here I found one solution for the problem: http://stackoverflow.com/questions/8623131/why-is-rand-not-so-random-after-fork – wonderingdev Apr 25 '16 at 19:40

1 Answers1

1

If you're on linux, you also seed the PRNG by reading from /dev/random. Something like this:

void seedprng() {
    unsigned i;
    FILE* f = open("/dev/random", "rb");
    if (f) {
        fread(&i, sizeof(i), 1, f);
        fclose(f);
        }
    else{
        printf("falling back to time seeding\n");
        i = (unsigned)time(NULL);
        }
    srand(&i)
    }
user590028
  • 11,364
  • 3
  • 40
  • 57