Recommended way to initialize srand?

前端 未结 15 1839
夕颜
夕颜 2020-11-22 08:07

I need a \'good\' way to initialize the pseudo-random number generator in C++. I\'ve found an article that states:

In order to generate random-like

15条回答
  •  滥情空心
    2020-11-22 08:35

    As long as your program is only running on Linux (and your program is an ELF executable), you are guaranteed that the kernel provides your process with a unique random seed in the ELF aux vector. The kernel gives you 16 random bytes, different for each process, which you can get with getauxval(AT_RANDOM). To use these for srand, use just an int of them, as such:

    #include 
    
    void initrand(void)
    {
        unsigned int *seed;
    
        seed = (unsigned int *)getauxval(AT_RANDOM);
        srand(*seed);
    }
    

    It may be possible that this also translates to other ELF-based systems. I'm not sure what aux values are implemented on systems other than Linux.

提交回复
热议问题