cposix-selecttimeval

Time returned by timeval structure is wrong in Ubuntu


I am trying to see the time taken by select function to moniter files, but when I try to print it, I get a very long number.Here is the code:

struct timeval to;
to.tv_usec=25;
nfds=select(maxfds+1,&readset,NULL,NULL,&to);
printf("Time left for monitering the file descriptors %d\n",to);

What is the reason for this weird behavior? This is code works fine with to.tv_sec.

enter image description here

Regards


Solution

  • You cannot pass a struct to printf() that way. Pass one of its members or a value created from them.

    If you trace the definition of a timeval struct down to implementation-specific detail, you will likely find something like this:

    struct timeval
      {
        __time_t tv_sec;    /* Seconds.  */
        __suseconds_t tv_usec;  /* Microseconds.  */
      };
    

    What this says is that there is a construct in memory which (at least on this particular platform) consists of a value in seconds followed in memory by a value of microseconds. These two values constitute the members of the struct.

    A function such as select() needs to be given a pointer to the struct itself. A pointer to the first member might often have the same raw memory address as its value, but is not formally or portably interchangeable and should result in warnings if misused as a struct pointer.

    A generic plain-value function like printf() has no knowledge of timeval structs, and so must be given either struct members which can be interpreted as numeric types which it does understand, or values created by combining struct members. For example, it's quite common to use both fields to calculate a 64-bit time in milliseconds and display that with 64-bit printf format specifier.