home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume25 / letters / usleep5.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-01-02  |  1.5 KB  |  47 lines

  1.     /*
  2.      * subseconds sleeps for System V - or anything that has poll() Don
  3.      * Libes, 4/1/1991
  4.      * 
  5.      * The BSD analog to this function is defined in terms of microseconds
  6.      * while poll() is defined in terms of milliseconds.  For
  7.      * compatibility, this function provides accuracy "over the long run"
  8.      * by truncating actual requests to milliseconds and accumulating
  9.      * microseconds across calls with the idea that you are probably
  10.      * calling it in a tight loop, and that over the long run, the error
  11.      * will even out.
  12.      * 
  13.      * If you aren't calling it in a tight loop, then you almost certainly
  14.      * aren't making microsecond-resolution requests anyway, in which
  15.      * case you don't care about microseconds.  And if you did, you
  16.      * wouldn't be using UNIX anyway because random system indigestion
  17.      * (i.e., scheduling) can make mincemeat out of any timing code.
  18.      * 
  19.      * Returns 0 if successful timeout, -1 if unsuccessful.
  20.      * 
  21.      */
  22.  
  23. #include <poll.h>
  24.  
  25.     int
  26.                     usleep(usec)
  27.     unsigned int    usec;    /* microseconds */
  28.     {
  29.         static          subtotal = 0;    /* microseconds */
  30.         int             msec;    /* milliseconds */
  31.  
  32.         /*
  33.          * 'foo' is only here because some versions of 5.3 have a bug
  34.          * where the first argument to poll() is checked for a valid
  35.          * memory address even if the second argument is 0.
  36.          */
  37.         struct pollfd   foo;
  38.  
  39.         subtotal += usec;
  40.         /* if less then 1 msec request, do nothing but remember it */
  41.         if (subtotal < 1000)
  42.             return (0);
  43.         msec = subtotal / 1000;
  44.         subtotal = subtotal % 1000;
  45.         return poll(&foo, (unsigned long) 0, msec);
  46.     }
  47.