c - 找不到 C 中的 getrandom 系统调用

标签 c linux ubuntu gcc system-calls

问题已通过升级 C 库解决。


我想使用系统调用 getrandom ( http://man7.org/linux/man-pages/man2/getrandom.2.html )

gcc-5 -std=c11 测试.c

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <linux/random.h>
#include <sys/syscall.h>

int main(void)
{
        void *buf = NULL;
        size_t l = 5;
        unsigned int o = 1;
        int r = syscall(SYS_getrandom, buf, l, o);
        return 0;
}

 int main(void)
    {
            void *buf = NULL;
            size_t l = 5;
            unsigned int o = 1;
            int r = getrandom(buf, l, o);
            return 0;
    }

无论如何,当我尝试用 gcc-5 编译它时:

test.c: In function ‘main’:
test.c:14:17: warning: implicit declaration of function ‘getrandom’ [-Wimplicit-function-declaration]
         int r = getrandom(buf, l, o);
                 ^
/tmp/ccqFdJAJ.o: In function `main':
test.c:(.text+0x36): undefined reference to `getrandom'
collect2: error: ld returned 1 exit status

我正在使用 Ubuntu 14.04,如何使用 getrandom? 由于它是一个"new"系统调用,我该如何使用它?

编辑:

uname -r
-> 4.0.3-040003-generic #201505131441 SMP Wed May 13 13:43:16 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

当我将 r 替换为 int r = syscall(SYS_getrandom, buf, l, o); 或者 r = getrandom(buf, l, o) 是一样的..

最佳答案

getrandom and getentropy were added to glibc in version 2.25 .截至 2017 年 7 月,大多数 Linux 发行版尚未更新到此版本(例如 Debian 的最新版本,刚刚发布,有 2.24),但他们应该很快。

以下是如何使用可用的 glibc 包装器,如果不可用则回退到原始系统调用:

#define _GNU_SOURCE 1
#include <sys/types.h>
#include <unistd.h>

#if defined __GLIBC__ && defined __linux__

# if __GLIBC__ > 2 || __GLIBC_MINOR__ > 24
#  include <sys/random.h>

int
my_getentropy(void *buf, size_t buflen)
{
    return getentropy(buf, buflen);
}

# else /* older glibc */
#  include <sys/syscall.h>
#  include <errno.h>

int
my_getentropy(void *buf, size_t buflen)
{
    if (buflen > 256) {
        errno = EIO;
        return -1;
    }
    return syscall(SYS_getrandom, buf, buflen, 0);
}

# endif

#else /* not linux or not glibc */
#error "Need implementation for whatever operating system this is"

#endif

(正如其他答案中所指出的,还需要确保您拥有 3.17 或更高版本的内核。以上两个版本的 my_getentropy 都会失败并将 errno 设置为ENOSYS 如果在较旧的内核上运行。)

关于c - 找不到 C 中的 getrandom 系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30800331/

相关文章:

C 中命令行参数的动态内存分配的混淆

c++ - windows平台下c++休眠线程100.8564毫秒

xml - AIX 中最简单的嵌套 XML 解析

linux - Docker 容器 crontab 未运行

python - 我们如何在同一 Ubuntu 操作系统上分别使用、维护和安装 python 2.7 和 python 3.5 的库?

ubuntu - ASP.NET Core 测试 : site can't be reached

c - 有没有办法禁用cmd中的右键菜单?

c - 插入排序不打印 C 中的所有值

php - 打开 Office 进行 doc、docx 和 rtf 到 html 的转换

linux - 无法与 Ubuntu Linux 机器建立 SSL 连接