Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When could a call to time(NULL) fail on Linux

Tags:

c

time

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.

like image 725
Salgar Avatar asked Oct 15 '09 11:10

Salgar


2 Answers

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;
}
like image 112
atomice Avatar answered Oct 06 '22 20:10

atomice


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.

like image 27
Alex B Avatar answered Oct 06 '22 20:10

Alex B