• 【Linux】【开发】Linux环境下如何在代码中产生随机数


    • 🐚作者简介:花神庙码农(专注于Linux、WLAN、TCP/IP、Python等技术方向)
    • 🐳博客主页:花神庙码农 ,地址:https://blog.csdn.net/qxhgd
    • 🌐系列专栏:Linux技术
    • 📰如觉得博主文章写的不错或对你有所帮助的话,还望大家三连支持一下呀!!! 👉关注✨、点赞👍、收藏📂、评论。
    • 如需转载请参考转载须知!!

    用户态

    rand和srand函数

    • 使用标准库stdlib.h中的rand()函数(ISO C标准函数), 其返回的随机数范围为:[0…RAND_MAX]。其函数原型为:
       #include 
       int rand(void);
       void srand(unsigned int seed);
    
    • 1
    • 2
    • 3
    • 如果未显式调用 srand,则相当于 srand(1),一个简单示例如下:
    #include 
    #include 
    
    int main(void)
    {
        printf("Random number is:  %d ", rand());
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 为了增加随机性,可显式调用srand函数:
    #include 
    #include 
    #include 
    
    int main () {
       int i, n;
       time_t t;
       
       n = 5;
       
       /* Intializes random number generator */
       srand((unsigned) time(&t));
    
       /* Print 5 random numbers from 0 to 50 */
       for( i = 0 ; i < n ; i++ ) {
          printf("%d\n", rand() % 50);
       }
       
       return(0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 也可以利用rand生成随机浮点数,一个例子如下:
    #include 
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
        srand((unsigned int)time(NULL));
    
        float a = 5.0;
        for (int i=0;i<20;i++)
            printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 值得一提的是rand不是线程安全的函数,替代品rand_r是线程安全的。

    random函数和srandom函数

    • 这两个函数对应于rand和srand两个函数,但却是线程安全的函数。
    #include 
    long random(void);
    void srandom(unsigned seed);
    
    • 1
    • 2
    • 3

    rand_r函数

    • rand_r()是POSIX.1扩展了C标准的函数,其返回范围为[0,RAND_MAX]的伪随机整数。 seed参数是一个指向无符号int的指针,该int用于存储两次调用之间的状态。该函数是线程安全的函数。
    #include 
    int rand_r (unsigned int *seed)
    • 1
    • 2

    /dev/random或/dev/urandom文件

    • /dev/random或/dev/urandom文件是 Linux 上的字符设备文件;
    • /dev/urandom 是伪随机数生成器pseudo random number generator(PRND),而 /dev/random 是“真”随机数生成器。
    • /dev/random可能会阻塞,/dev/urandom才是类 Unix 操作系统下推荐的加密种子。
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
      
    #define RANDPATH "/dev/random"
      
    int main()
    {
        int fp, ret;
        unsigned int rand;
      
        // Open as read only
        fp = open(RANDPATH, O_RDONLY);
        if(fp < 0){
            fprintf(stderr, "Could not open -%s- for reading.\n",RANDPATH);
            return -1;
        }
      
        ret = read(fp, &rand, sizeof(rand));
            if(ret < 0){
                    fprintf(stderr, "Could not read from -%s-.\n",RANDPATH);
                    close(fp);
                    return ret;
            }
      
        fprintf(stdout, "Random value: %u\n", rand % 10); // Range from 0 to 10
        close(fp);  
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    getrandom函数

    • 本质上是从/dev/random或/dev/urandom文件中获取,对应一个系统调用, 在linux kernel 3.17中引入。
    • 函数原型:
       #include 
       ssize_t getrandom(void buf[buflen], size_t buflen, unsigned int flags);
    
    • 1
    • 2

    内核态

    • get_random_bytes 是 Linux 内核中的一个函数,它用于生成随机字节序列的系统调用。以下是该函数的原型:
    #  `buf`:指向要填充随机字节的缓冲区的指针。
    #  `nbytes`:要生成的随机字节数。
    void  get_random_bytes(void  *buf, int nbytes);
    
    • 1
    • 2
    • 3

    参考资料

    如本文对你有些许帮助,欢迎大佬加关注、评论、点赞,有关必回关

  • 相关阅读:
    大模型Prompt-Tuning技术入门
    数仓分层能减少重复计算,为啥能减少?如何减少?这篇文章包懂!
    Technology strategy Pattern 学习笔记1-Context: Architecture and Strategy
    五.Kafka入门到精通-深度剖析Kafka执行原理
    Electron结合React和TypeScript进行开发
    如何将DHTMLX Suite集成到Scheduler Lightbox中?让项目管理更可控!
    HBuilder X实现banner轮播图
    前端常用网址总结
    SpreadJS 15.1 CN 与 SpreadJS 15.1 EN
    VUE系列 --- 网络模块axios(三)
  • 原文地址:https://blog.csdn.net/qxhgd/article/details/132302260