问题描述
问题已通过升级 C 库解决.
我想使用系统调用 getrandom (http://man7.org/linux/man-pages/man2/getrandom.2.html)
I would like to use the syscall getrandom (http://man7.org/linux/man-pages/man2/getrandom.2.html)
gcc-5 -std=c11 test.c
gcc-5 -std=c11 test.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 编译它时:
Anyway when I try to compile it with 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?由于它是一个新的"系统调用,我该如何使用它?
I am using Ubuntu 14.04, what can I do to use getrandom?As it is a "new" syscall, how can I use it?
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
当我用 int r = syscall(SYS_getrandom, buf, l, o); 替换 r 时;
或 r = getrandom(buf, l, o) 是一样的..
when I replace r by int r = syscall(SYS_getrandom, buf, l, o);
or r = getrandom(buf, l, o) it is the same..
推荐答案
getrandom
和 getentropy
在 2.25 版中被添加到 glibc.截至 2017 年 7 月,大多数 Linux 发行版尚未更新到此版本(例如,Debian 刚刚发布的最新版本有 2.24),但它们应该很快就会更新.
getrandom
and getentropy
were added to glibc in version 2.25. As of July 2017, most Linux distributions have not yet updated to this version (e.g. Debian's most recent release, which just came out, has 2.24) but they should soon.
以下是如何使用 glibc 包装器(如果可用)并返回到原始系统调用(如果没有):
Here is how to use the glibc wrappers if available and fall back to the raw system call if not:
#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
如果在旧内核上运行.)
(As pointed out in other answers, it is also necessary to ensure you have kernel 3.17 or newer. Both the above versions of my_getentropy
will fail and set errno
to ENOSYS
if run on an older kernel.)
这篇关于找不到 C 中的 getrandom 系统调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!