/* spin.c Equivalent to "sleep" except that resolution is milliseconds instead of seconds. Written by David Horton 6-Jan-92 Bugs: This consumes CPU resource */ #include #ifndef _INCLUDE_POSIX_SOURCE #define _INCLUDE_POSIX_SOURCE #endif #ifndef _INCLUDE_HPUX_SOURCE #define _INCLUDE_HPUX_SOURCE #endif #include #include main (int argc, char *argv[]) { int milli; /* milli seconds to spin for */ int secs; /* milli seconds part > 1000 */ struct timeval now; /* time at the present moment */ struct timeval then; /* when our time expires */ struct timezone us; /* unused */ if (argc != 2) { fprintf(stderr,"Usage: %s milliseconds\n", argv[0]); exit (1); } milli = atoi(argv[1]); /* see how long to sleep */ secs = milli / 1000; /* split into parts for structure */ milli = milli % 1000; if (gettimeofday(&now, &us)){ /* when is that in the future */ perror("gettimeofday"); exit (errno); } then.tv_usec = now.tv_usec + milli * 1000; /*we'll fix the wrap next*/ then.tv_sec = now.tv_sec + secs + then.tv_usec / 1000000; then.tv_usec = then.tv_usec % 1000000; # ifdef DEBUG printf("now %d.%6d, then %d.%6d\n", now.tv_sec, now.tv_usec, then.tv_sec, then.tv_usec); # endif while (timercmp(&now, &then, <)) { /* is the time up yet ? -> busy wait */ if (gettimeofday(&now, &us)){ /* when is that in the future */ perror("gettimeofday"); exit (errno); } } # ifdef DEBUG printf("now %d.%6d, then %d.%6d\n", now.tv_sec, now.tv_usec, then.tv_sec, then.tv_usec); # endif exit(0); }