Chinaunix

标题: srand,random的疑问 [打印本页]

作者: hkdjining    时间: 2006-05-28 19:46
标题: srand,random的疑问
如果在linux下,用ticks = tv.tv_sec + tv.tv_usec;然后fd=open("/dev/urandom",O_RDONLY);接着进行了一个循环for (i=0;i<512;i++)
            {
              read(fd, &r, sizeof(r));
              ticks += r;
            }
然后用ticks做种子,我不明白打开那个文件并循环的目的是什么?只用ticks = tv.tv_sec + tv.tv_usec;难道不行吗?这个函数是不是能保证每次生成的随机数都不一样啊?还忘高手指教,谢谢了!
static unsigned int random_seed_set = 0;
unsigned int
osip_build_random_number ()
{
  if (!random_seed_set)
    {
      unsigned int ticks;
#ifdef WIN32
      LARGE_INTEGER lCount;
      QueryPerformanceCounter(&lCount);
      ticks = lCount.LowPart + lCount.HighPart;
#elif defined(_WIN32_WCE)
      ticks = GetTickCount();
#else
      struct timeval tv;
      int fd;
      gettimeofday (&tv, NULL);
      ticks = tv.tv_sec + tv.tv_usec;
      fd=open("/dev/urandom",O_RDONLY);
      if (fd > 0)
        {
          unsigned int r;
          int i;
          for (i=0;i<512;i++)
            {
              read(fd, &r, sizeof(r));
              ticks += r;
            }
          close(fd);
        }
#endif

#ifdef HAVE_LRAND48
      srand48 (ticks);
#else
      srand (ticks);
#endif
      random_seed_set = 1;
    }

#ifdef HAVE_LRAND48
  return lrand48 ();
#else
  return rand ();
#endif
}




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2