【发布时间】:2015-02-02 20:37:14
【问题描述】:
手册页man 2 time 说:
SYNOPSIS
#include <time.h>
time_t time(time_t *t);
RETURN VALUE
On success, the value of time in seconds since the Epoch is returned. On error,
((time_t) -1) is returned, and errno is set appropriately.
ERRORS
EFAULT t points outside your accessible address space.
我有一个简单的测试设置,试图从该函数中强制出错 - 应该是有史以来最直接的事情:
time_t *ptr = (time_t *) 0xabad1dea;
time_t secs = time(ptr);
if (secs == ((time_t) -1)) /* Not caught */
exit(EXIT_FAILURE);
printf("Number of seconds since the Epoch: %lld\n", secs);
printf("It should return ((time_t) -1) on error: %lld\n", (time_t) -1);
secs = *ptr; /* This *does* segfault */
由于某种原因,time() 在我的系统上返回 -14 而不是 -1。我完全被难住了。甚至感到困惑。
我怀疑任何人都可以重现此问题,但有没有人知道我到底为什么会出现这种行为?如果是这样,我非常好奇!
编辑:我知道时间并没有取消引用我传递的错误指针,因为这会使程序崩溃。手册页确实说如果地址不可访问,它应该返回 -1 并设置 errno。 EFAULT 为 14,但没有返回 -EFAULT not 此处定义的 time() 是什么?
【问题讨论】:
-
正如预期的那样,你得到了 EFAULT,这在 linux 上是错误 #14
-
@MarcB 可能是它,但它会违反手册,其中指出 errno 设置为 EFAULT 并返回 (time_t)-1。
-
@MarcB:可能需要将
errno设置为EFAULT。 返回-EFAULT不是。 -
"%lld"需要long long类型的参数。尝试转换参数:printf("... %lld\n", (long long)secs);。唔。如果time_t比您系统上的long long窄,printf可能会从相邻内存中获取-14。
标签: c linux time system-calls