0

I have a snippet below - I've adjusted my tv_usec in several ways, but I keep sitting in a select() loop for almost exactly 10 seconds, regardless of what tv_usec is set at.

    char buffer[512];
    fd_set readfds;
    struct timeval tv;
    tv.tv_usec = 50;    

    int rv = 1;

    // clear the set ahead of time
    FD_ZERO(&readfds);

    // add our descriptors to the set
    FD_SET(mySocket, &readfds);

    // the n param for select()
    int n = mySocket + 1;

    while(rv != 0)
    {
        rv = select(n, &readfds, NULL, NULL, &tv);

        if (rv == -1)
            perror("select"); // error occurred in select()

        bzero(buffer,512);
        int n = recvfrom(mySocket,buffer,512,0,(struct sockaddr *)&server, &sockLen);

        // do stuff...
    }
MrDuk
  • 16,578
  • 18
  • 74
  • 133

1 Answers1

6

tv.tv_sec needs to be initialized to something. Setting tv.tv_sec = 0 solved the issue.

MrDuk
  • 16,578
  • 18
  • 74
  • 133
  • 1
    It's not that it defaults to 10, it's that uninitialised memory may have arbitrary prior content - it's actually undefined behaviour to read it. – Tony Delroy Mar 18 '14 at 05:01
  • 1
    It actually doesn't default to anything. If you don't set the value, it will contain whatever value happened to be in that memory location at the time, i.e. an undefined value. – Jeremy Friesner Mar 18 '14 at 05:02
  • Ahh, very interesting. I wonder why it was always right at 10 seconds. – MrDuk Mar 18 '14 at 05:08
  • @MrDuk: well, your `timeval` structure's on the stack, and the stack content may be set to specific values by prior stack usage, such as values prepared for earlier function calls. It's hard to see why it would be deterministic without seeing the program. But, if you do something like add a variable between `readfds` and `ts`, add a function call in somewhere, or compile with different optimisation flags, you could easily see a totally different and possibly varying value. – Tony Delroy Mar 18 '14 at 05:33
  • Keep in mind that `timeval` is a structure from the C library header, and C structures never have automatic constructors (at best there's some function like `pthread_mutex_init` you have to manually call to "construct" them, otherwise you can assign them an initial value ideally immediately after their definition so it's easier to check it's done consistently). – Tony Delroy Mar 18 '14 at 05:34