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

后端 未结 3 996
深忆病人
深忆病人 2020-12-10 13:02

I have to write a C program which has to sleep for milliseconds, which has to run on various platforms like Windows, Linux, Solaris, HP-UX, IBM AIX, Vxworks, and Windriver L

3条回答
  •  情深已故
    2020-12-10 13:40

    Propably a wrapper using platform specific #defines will do:

    #if defined(WIN32)
      #include 
    #elif defined(__UNIX__)
      #include 
    #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, please find a more modern, more portable (and as well corrected :}) version here:

    #if defined(WIN32)
      #include 
    #elif defined(__unix__)
      #include 
      #include 
    #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
    }
    

提交回复
热议问题