[racket] FFI question: 0 microseconds returned from gettimeofday call

From: Thomas Chust (chust at web.de)
Date: Thu Jul 14 17:01:54 EDT 2011

keydana at gmx.de wrote:
> [...]
> In fact I'd assume that using _int for suseconds_t should work fine, too, given that man even tells us that
> "The values in timeval are opaque types whose length may vary on different machines; depending on
>      them to have any given length may lead to errors."
> [...]

Hello Sigrid,

unfortunately, if the man page really says that, it means that whatever
fixed type you specify in Racket's FFI, it might break on some system
:-/ Perhaps _long or _intptr would be a better choice than _int, since
they would adapt to the system's word size, which is more likely to be
right everywhere than _int that is always 32 bits wide, according to the
Racket documentation, but you can't be sure.

There is, however, a PLaneT package (planet dherman/c:4:0) providing the
facilities to parse header files and extract structure layout
information like that required here using the system's C compiler.

> [...]
> So, I wonder if there is a different kind of error in my code:
> (define libsys (ffi-lib "libsystem"))
> (define-cstruct _timeval ((secs _int) (μsecs _int)))
> (define-cstruct _timezone ((minswest _int) (dsttime _int)))
> (define gettimeofday (get-ffi-obj "gettimeofday" libsys (_fun (tm : (_ptr o _timeval)) (tz : (_ptr o _timezone)) -> _int -> (values (timeval-secs tm) (timeval-μsecs tm) (timezone-minswest tz) (timezone-dsttime tz)))))
> (gettimeofday)
> leading to the output
> 1310672543
> 0
> -60
> 1
> [...]

The zero microseconds value could mean that you were actually "lucky"
with the call, that your system simply doesn't support time values with
microsecond precision or that your system's implementation of
gettimeofday doesn't support that.

By the way, I think that the dsttime field in _timezone should probably
have the type _bool. But the POSIX standard says anyway that if the
second argument to gettimeofday is anything else than the null pointer,
the behaviour of the whole function call is undefined, so you have no
right to complain no matter how strange the result is ;-)

> [...]
> Also, I am confused by the coexistence of _xxx.h and xxx.h header files (like sys/types.h and _types.h), and I wonder what is the signification of single and double underscores in variables defined in the header files - could anyone perhaps point me to a resource documenting these conventions?
> [...]

Well, the usual convention seems to be that identifiers starting with
underscores are "private" in some sense and should only be accessed by
code that feels entitled to, identifiers starting with two underscores
may be "special" in some sense and should usually not be used at all by
mere mortals ;-)

Welcome to the world of C -- I guess my e-mail signature sums up the
situation in this case, too ;-)


When C++ is your hammer, every problem looks like your thumb.

Posted on the users mailing list.