Sleeping in milliseconds on Windows, Linux, Solaris, HP-UX, IBM AIX, Vxworks, Wind River Linux?

I need to write a C program that should sleep for milliseconds, which should work on different platforms such as Windows, Linux, Solaris, HP-UX, IBM AIX, Vxworks, and Windriver Linux.

  • On Windows, the Sleep system call will only work in milliseconds.
  • On Linux , Sleep will work in seconds; usleep will run on microseconds as well as on Solaris.
  • In Vxworks , I hope I can implement it using taskDelay and sysClkRateSet .

How can I achieve this millisecond sleep on HP-UX, IBM AIX, and Wind River Linux?

+7
source share
2 answers

A simplified shell using a specific #define platform will do:

 #if defined(WIN32) #include <windows.h> #elif defined(__UNIX__) #include <unistd.h> #else #endif ... int millisleep(unsigned ms) { #if defined(WIN32) SetLastError(0); Sleep(ms); return GetLastError() ?-1 :0; #elif defined(LINUX) return usleep(1000 * ms); #else #error ("no milli sleep available for platform") return -1; #endif } 

Update

Referring to Jonathan's comment below , find a more modern, more portable (and also fixed :) version here:

 #if defined(WIN32) #include <windows.h> #elif defined(__unix__) #include <time.h> #include <unistd.h> #else #endif ... int millisleep(unsigned ms) { #if defined(WIN32) SetLastError(0); Sleep(ms); return GetLastError() ?-1 :0; #elif _POSIX_C_SOURCE >= 199309L /* prefer to use nanosleep() */ const struct timespec ts = { ms / 1000, /* seconds */ (ms % 1000) * 1000 * 1000 /* nano seconds */ }; return nanosleep(&ts, NULL); #elif _BSD_SOURCE || \ (_XOPEN_SOURCE >= 500 || \ _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) && \ !(_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700) /* else fallback to obsolte usleep() */ return usleep(1000 * ms); #else # error ("No millisecond sleep available for this platform!") return -1; #endif } 
+13
source

Consider select with empty FD sets and the required latency. From man select :

Some select () code calls with all three sets empty, nfds zero and non-NULL timeout as a fairly portable way to sleep with sub-second precision.

In fact, this may be the best solution for any system other than Windows.

+1
source

All Articles