Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added further information about system clock resolution, removed warning about 15 year old POSIX implementations

...

Call srandom() before invoking random() to seed the random sequence generated by random(). This compliant solution produces different random number sequences each time the program is runfunction is called, depending on the resolution of the system clock:

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
void func(void) {
  struct timespec ts;
  if (timespec_get(&ts, TIME_UTC) == 0) {
    /* Handle error */
  }
  else {
    srandom(ts.tv_nsec ^ ts.tv_sec);
    for (unsigned int i = 0; i < 10; ++i) {
      /* Generates different sequences at different runs */
      printf("%ld, ", random());
    }
  }
}

...

This may not be sufficiently random for concurrent execution, which may lead to correlated generated series in different threads, or for small embedded systems that have an unsigned int type with a width of 16 bits. (The POSIX standard specifies a minimum width of 32 bits for unsigned int. However, prior to the 2001 edition, POSIX.1 allowed 16 bit unsigned int).  Depending . Depending on the application and the desired level of security, a programmer may choose alternative ways to seed PRNGs. In general, hardware is more capable than software of generating real random numbers (for example, by sampling the thermal noise of a diode).

...