crandomnumbersgenerator

Pseudorandom number generator in C - seeding with time functions


So I'm attempting to create a pseudorandom number generator that will return a RN in a specified range for use later in my program.

Unfortunately, my compiler (gcc) will not recognize the type "time_t", the function "time()", etc. I thought I had included the right headers - but still having errors compiling. I may just be tired, but Googling the error didn't result in helpful information - so I turn to the great stackoverflow. My apologies if the problem simple and I just overlooked it...

my include statements:

#include "param.h"
#include "mmu.h"
#include "x86.h"
#include "proc.h"
#include "spinlock.h"
#include "pstat.h"
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

The RNG:

static int random_range (unsigned int min, unsigned int max){
    // Get value from system clock and place in seconds variable
    time_t seconds;
    // Convert seconds to a unsigned integer.
    time(&seconds);
    // Set seed
    srand((unsigned int) seconds);

    int base_r = rand(); 
    if (RAND_MAX == base_r) return random_range(min, max);
      // now guaranteed to be in [0, RAND_MAX) 
        int range       = max - min,
        int remainder   = RAND_MAX % range,
        int bucket      = RAND_MAX / range;
      // There are range buckets, plus one smaller interval within remainder of RAND_MAX 
        if (base_random < RAND_MAX - remainder) {
            return min + base_random/bucket;
        }

    else return random_in_range (min, max);

}

compiler errors relating to the above - not all since I'm sure I'm missing some include statement, or similar:

kernel/proc.c:9:18: error: time.h: No such file or directory
kernel/proc.c:10:20: error: stdlib.h: No such file or directory
kernel/proc.c:11:19: error: stdio.h: No such file or directory
kernel/proc.c: In function ‘random_range’:
kernel/proc.c:31: error: ‘time_t’ undeclared (first use in this function)
kernel/proc.c:31: error: (Each undeclared identifier is reported only once
kernel/proc.c:31: error: for each function it appears in.)
kernel/proc.c:31: error: expected ‘;’ before ‘seconds’

Solution

  • Ahhh... I think I got it:

    xv6 can't use the stdlib function calls. I'll have to create my own random function.

    Any suggestions? Please link me... I know that there's something out there called "something"-twister that's supposed to be good.