tags:

views:

147

answers:

4

According to this documentation http://www.cplusplus.com/reference/clibrary/ctime/time/

for time(NULL) "If the function could not retrieve the calendar time, it returns a -1 value."

Is this something I should check for in my code? Surely something has got to be going pretty wrong if time(NULL) is not retrieving the time.

+2  A: 

Ubuntu man page says time(2) can fail due to EFAULT ("t points outside your accessible address space").

OSX man page says it can fail for the same reasons as gettimeofday, which are EFAULT and EPERM (not sure how this applies to time).

Therefore, it cannot fail for the argument of NULL, according to the documentation of aforementioned systems.

Also, POSIX specifies no error conditions at all for this function.

Alex B
The question is about when t is NULL.
HMage
Well, then it won't fail?
Alex B
A: 

You have something called a system clock. If that's broken, then this will fail, though there could be many other reasons.

Aviral Dasgupta
How can the system clock "break"? I've seen it lose time, gain time, and behave abnormally. But I've never seen it not work at all.
Thomas Owens
Reference to atomice's post : If you use this for say --- the nds (www.devkitpro.com) then it *CAN* (Downvoter explain yourself)
Aviral Dasgupta
+14  A: 

You may be running on an embedded device that doesn't have a real-time clock.

The glibc source code claims that the time syscall can't fail on Linux:

 time_t res = INTERNAL_SYSCALL (time, err, 1, NULL);
  /* There cannot be any error.  */

and indeed this is the case if you look at the kernel source:

SYSCALL_DEFINE1(time, time_t __user *, tloc)
{
        time_t i = get_seconds();

        if (tloc) {
                if (put_user(i,tloc))
                        return -EFAULT;
        }
        force_successful_syscall_return();
        return i;
}
atomice
+1 for taking a look in the manual and the kernel
Tobias Langner
+1. To reinforce: Not all devices have a clock.
DevSolar
A: 

The obvious case would be a system whose internal clock requires external initialization (using eg. NTP). Until this has happened, the internal clock cannot give epoch-relative values, although it can be used to measure intervals. time_t is epoch-relative and therefore time(NULL) must fail in this case.

MSalters
wouldn't time(NULL) just give the wrong answer here? Rather than failing and returning -1?
Managu
No, not if it's properly implemented. That's quite reasonable. Consider an OS that implements a `/dev/time/` deivce, which when read gives the current time. Until initialized, you'd get a read error on the device. A standard C lib would pass on that failure when calling `time()`
MSalters