Search code examples
cposix

Under what circumstances can time in time.h fail?


The time function in the header time.h is defined by POSIX to return a time_t which can, evidently, be a signed int or some kind of floating point number.

http://en.cppreference.com/w/c/chrono/time

The function, however, returns (time_t)(-1) on error.

Under what circumstances can time fail?

Based on the signature, time_t time( time_t *arg ) it seems like the function shouldn't allocate, so that strikes one potential cause of failure.


Solution

  • The time() function is actually defined by ISO, to which POSIX mostly defers except it may place further restrictions on behaviour and/or properties (like an eight-bit byte, for example).

    And, since the ISO C standard doesn't specify how time() may fail(a), the list of possibilities is not limited in any way:

    • One way in which it may fail is in the embedded arena. It's quite possible that your C program may be running on a device with no real-time clock or other clock hardware (even a counter), in which case no time would be available.
    • Or maybe the function detects bad clock hardware that's constantly jumping all over the place and is therefore unreliable.
    • Or maybe you're running in a real-time environment where accesses to the clock hardware are time-expensive so, if it detects you're doing it too often, it decides to start failing so your code can do what it's meant to be doing :-)

    The possibilities are literally infinite and, of course, I mean 'literally' in a figurative sense rather than a literal one :-)


    POSIX itself calls out explicitly that it will fail if it detects the value won't fit into a time_t variable:

    The time() function may fail if: [EOVERFLOW] The number of seconds since the Epoch will not fit in an object of type time_t.


    And, just on your comment:

    Based on the signature, time_t time( time_t *arg ), it seems like the function shouldn't allocate.

    You need to be circumspect about this. Anything not mandated by the standards is totally open to interpretation. For example, I can envisage a bizarre implementation that allocates space for an NTP request packet to go out to time.nist.somewhere.org so as to ensure all times are up to date even without an NTP client :-)


    (a) In fact, it doesn't even specify what the definition of time_t is so it's unwise to limit it to an integer or floating point value, it could be the string representation of the number of fortnights since the big bang :-) All it requires is that it's usable by the other time.h functions and that it can be cast to -1 in the event of failure.

    POSIX does state that it represents number of seconds (which ISO doesn't) but places no other restrictions on it.