0

I have used select call in my prog and it works on most of unix flavors. However, It works on one HPUX ia64 box but another it timeout immediately.

After several re-builds, I understood that i have set tv_sec but not set tv_usec of timeval structure. After setting tv_usec member of timeval structure to 0, it start working on all platform.

But, I didn't understood the reason for why program was behaving differently for same OS ? and how problem solved only by settting tm.tv_usec = 0?

j0k
  • 22,600
  • 28
  • 79
  • 90
Sach
  • 659
  • 8
  • 20
  • If the `struct timeval` structure is allocated on the stack or dynamically, and not explicitly initialised to `0`, there will be random garbage in `tv.tv_usec`. – Blagovest Buyukliev Nov 23 '11 at 12:26

1 Answers1

2

tv_sec and tv_usec are signed int values so they can be negative numbers.

If your struct is a local variable it will contain whatever happens to be on the stack.

In select, the seconds part of the time is calculated like this (taken from the Linux source code):

  tv.tv_sec + (tv.tv_usec / USEC_PER_SEC)

As you can see, no check is made that the numbers are positive so if the uninitialised variable should happen to contain a big negative number, the select will return immediately.

Edit:

The use of an uninitialised variable results in undefined behaviour. That select returns immediately on one machine and not on another is therefore within the C specification.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • tv_sec is time_t - an unsigned value, assuming POSIX compliance. – jim mcnamara Nov 23 '11 at 14:42
  • @Klas- I have debug the binary and tv_usec never been a negative number. And if it is non-negative number, select should not exit before specified time according to addition logic. – Sach Nov 28 '11 at 14:12
  • @Klas: Also want to add that, it works on linux without setting tv_usec to 0. it works on HP-UX as well but need to remove hpux related compilation options. – Sach Nov 28 '11 at 14:14
  • HPUX isn't open source, so the actual source code for HPUX select isn't available. I was jaust giving a possible explanation to the observed behaviour. Even if tv_usec is declared as an unsigned entity in HPUX, the calculation of the time could still be signed. – Klas Lindbäck Nov 28 '11 at 14:37
  • POSIX XSI requires that `tv_usec` has a signed integer type capable of storing values at least in the range [-1, 1000000]. – mark4o Nov 28 '11 at 17:25