C 语言中是否有替代毫秒的睡眠函数?

发布于 2024-07-27 01:52:29 字数 291 浏览 3 评论 0原文

我有一些在 Windows 上编译的源代码。 我正在将其转换为在 Red Hat Linux 上运行。

源代码包含 头文件,并且程序员使用 Sleep() 函数等待一段毫秒时间。 这在 Linux 上不起作用。

但是,我可以使用 sleep(seconds) 函数,但它使用以秒为单位的整数。 我不想将毫秒转换为秒。 有没有可以在 Linux 上与 gcc 编译一起使用的替代睡眠函数?

I have some source code that was compiled on Windows. I am converting it to run on Red Hat Linux.

The source code has included the <windows.h> header file and the programmer has used the Sleep() function to wait for a period of milliseconds. This won't work on the Linux.

However, I can use the sleep(seconds) function, but that uses integer in seconds. I don't want to convert milliseconds to seconds. Is there a alternative sleep function that I can use with gcc compiling on Linux?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

似最初 2024-08-03 01:52:30

您可以使用这个跨平台功能:

#ifdef WIN32
#include <windows.h>
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h>   // for nanosleep
#else
#include <unistd.h> // for usleep
#endif

void sleep_ms(int milliseconds){ // cross-platform sleep function
#ifdef WIN32
    Sleep(milliseconds);
#elif _POSIX_C_SOURCE >= 199309L
    struct timespec ts;
    ts.tv_sec = milliseconds / 1000;
    ts.tv_nsec = (milliseconds % 1000) * 1000000;
    nanosleep(&ts, NULL);
#else
    if (milliseconds >= 1000)
      sleep(milliseconds / 1000);
    usleep((milliseconds % 1000) * 1000);
#endif
}

You can use this cross-platform function:

#ifdef WIN32
#include <windows.h>
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h>   // for nanosleep
#else
#include <unistd.h> // for usleep
#endif

void sleep_ms(int milliseconds){ // cross-platform sleep function
#ifdef WIN32
    Sleep(milliseconds);
#elif _POSIX_C_SOURCE >= 199309L
    struct timespec ts;
    ts.tv_sec = milliseconds / 1000;
    ts.tv_nsec = (milliseconds % 1000) * 1000000;
    nanosleep(&ts, NULL);
#else
    if (milliseconds >= 1000)
      sleep(milliseconds / 1000);
    usleep((milliseconds % 1000) * 1000);
#endif
}
最后的乘客 2024-08-03 01:52:30

或者 usleep() ,即POSIX 2008 中没有定义(尽管它是在 POSIX 2004 之前定义的,并且显然可以在 Linux 和其他具有 POSIX 合规历史的平台上使用),POSIX 2008 标准定义了 nanosleep()

nanosleep - 高分辨率睡眠

#include ; 
  int nanosleep(const struct timespec *rqtp, struct timespec *rmtp); 
  

nanosleep() 函数应导致当前线程暂停执行,直到 rqtp 参数指定的时间间隔已过或信号传递到调用线程,其动作是调用信号捕获函数或终止进程。 挂起时间可能比请求的时间长,因为参数值向上舍入为睡眠分辨率的整数倍,或者因为系统调度了其他活动。 但是,除了被信号中断的情况外,暂停时间不得小于rqtp指定的时间,由系统时钟CLOCK_REALTIME测量。

使用nanosleep()函数对任何信号的动作或阻塞没有影响。

Alternatively to usleep(), which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep():

nanosleep - high resolution sleep

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

記憶穿過時間隧道 2024-08-03 01:52:30

除了usleep之外,谦虚的select 与 NULL 文件描述符集将让您以微秒精度暂停,并且没有 SIGALRM并发症。

sigtimedwait 和 sigwaitinfo 提供类似的行为。

Beyond usleep, the humble select with NULL file descriptor sets will let you pause with microsecond precision, and without the risk of SIGALRM complications.

sigtimedwait and sigwaitinfo offer similar behavior.

又爬满兰若 2024-08-03 01:52:30
#include <unistd.h>

int usleep(useconds_t useconds); //pass in microseconds
#include <unistd.h>

int usleep(useconds_t useconds); //pass in microseconds
匿名。 2024-08-03 01:52:29

是 - 较旧的 POSIX 标准定义 usleep(),因此这在 Linux 上可用:

int usleep(useconds_t usec); 
  

描述

usleep() 函数暂停调用线程的执行
(至少)usec 微秒。 睡眠时间可能会稍微延长
任何系统活动或处理呼叫所花费的时间或
系统定时器的粒度。

usleep() 需要微秒,因此您必须将输入乘以 1000 才能以毫秒为单位休眠。


usleep() 已被弃用并随后从 POSIX 中删除; 对于新代码,nanosleep() 是首选:

#include ; 

  int nanosleep(const struct timespec *req, struct timespec *rem); 
  

描述

nanosleep() 挂起调用线程的执行,直到至少经过 *req 中指定的时间,或者
传递触发调用处理程序的信号
调用线程或终止进程。

结构体 timespec 用于指定纳秒精度的时间间隔。 其定义如下:

struct timespec { 
      time_t 电视_秒;   /* 秒 */ 
      长 tv_nsec;   /* 纳秒 */ 
  }; 
  

使用 nanosleep() 实现的示例 msleep() 函数,如果被信号中断则继续睡眠:

#include <time.h>
#include <errno.h>    

/* msleep(): Sleep for the requested number of milliseconds. */
int msleep(long msec)
{
    struct timespec ts;
    int res;

    if (msec < 0)
    {
        errno = EINVAL;
        return -1;
    }

    ts.tv_sec = msec / 1000;
    ts.tv_nsec = (msec % 1000) * 1000000;

    do {
        res = nanosleep(&ts, &ts);
    } while (res && errno == EINTR);

    return res;
}

Yes - older POSIX standards defined usleep(), so this is available on Linux:

int usleep(useconds_t usec);

DESCRIPTION

The usleep() function suspends execution of the calling thread for
(at least) usec microseconds. The sleep may be lengthened slightly by
any system activity or by the time spent processing the call or by the
granularity of system timers.

usleep() takes microseconds, so you will have to multiply the input by 1000 in order to sleep in milliseconds.


usleep() has since been deprecated and subsequently removed from POSIX; for new code, nanosleep() is preferred:

#include <time.h>

int nanosleep(const struct timespec *req, struct timespec *rem);

DESCRIPTION

nanosleep() suspends the execution of the calling thread until either at least the time specified in *req has elapsed, or the
delivery of a signal that triggers the invocation of a handler in the
calling thread or that terminates the process.

The structure timespec is used to specify intervals of time with nanosecond precision. It is defined as follows:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};

An example msleep() function implemented using nanosleep(), continuing the sleep if it is interrupted by a signal:

#include <time.h>
#include <errno.h>    

/* msleep(): Sleep for the requested number of milliseconds. */
int msleep(long msec)
{
    struct timespec ts;
    int res;

    if (msec < 0)
    {
        errno = EINVAL;
        return -1;
    }

    ts.tv_sec = msec / 1000;
    ts.tv_nsec = (msec % 1000) * 1000000;

    do {
        res = nanosleep(&ts, &ts);
    } while (res && errno == EINTR);

    return res;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文