C Help; generating a random number.

Im new to C, and Im having a hard time getting a random number.

In bash, I would do something similar to the following to get a random number;

#!/bin/bash
seed1=$RANDOM
seed2=$RANDOM
seed3=$RANDOM
SEED=`expr $seed1 * $seed2 / $seed3`

echo ${SEED%.*}

Now, in online examples for C everyone suggest seeding srandom with time, so I attempted seeding with time_t now. Which works great except this program will run probably 20-30 times a second... to seeding with time_t now wont work.. as I'll continually get the same random number.

How can a randomize better in c? IS there a way to get milliseconds or nanoseconds with time.h? I dont care if it's not 100% accurate I just need to figure out how to get a truly random number.

Do not reseed. Otherwise you keep getting the same value.

PNG's are setup to generate a series of random numbers from a single starting point. Reseeding before every call to rand() "undoes" that. IT does NOT randomize better.

From your 'truly random' statement I'm getting the idea that you may not know too much about random numbers generators and their limitations. Random means that you have an equal chance of getting any number, including the one you just got before. For rand() that means you are supposed to have an equal chance for any number 1 - RAND_MAX. rand() is not a great PNG.

Try lrand48(). It is somewhat better and is there on most all unix boxes.
-- Seed it only once.

Do not use any of these functions for cryptographic applications.

...but he should seed *once* -- or he'll get the same numbers anyway. I take "running 30 times per second" to mean 30 processes per second, and each process must seed once to get different numbers.

Yes, you can get seconds and microseconds from gettimeofday().

As Corona688 says,
If you use the same value to generate a "random" value, the algorithm is always going to perform the same operation with the same number, so, you need to parse values which are always going to be different, and yes, with gettimeofday() you can parse system time in nanoseconds to get a different number every nanosecond.

Try this:

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int main(void){
int i;
unsigned int value;
struct timeval tv;
struct timezone tz;
struct tm *tm;
tm = localtime(&tv.tv_sec);

for(i = 0;i < 30; i++){
gettimeofday(&tv, &tz);
value = rand_r(&tv.tv_usec);
printf("%i\n", value);
}
return(0);
}

The OP is using time(). RANDOM (in bash) doesn't call rand() it calls random() I believe.
My response was geared to using rand()

The best choice is either urandom() or random(). And yes you do seed once. But gettimeofday on a multiprocessor/multicore box with threads can have the same effect as calling time() - the same seed value. I saw that years ago on a 8-cpu HPUX PARISC box.