Linux C语言中是否有另一种睡眠函数到毫秒?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1157209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:32:24  来源:igfitidea点击:

Is there an alternative sleep function in C to milliseconds?

clinuxsleep

提问by ant2009

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

我有一些在 Windows 上编译的源代码。我正在将其转换为在 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.

源代码已包含<windows.h>头文件,程序员已使用该Sleep()函数等待一段时间。这在 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?

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

采纳答案by caf

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

是 - 已定义较旧的POSIX标准usleep(),因此可在 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.

   int usleep(useconds_t usec);

描述

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

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

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



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

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

   #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 *reqhas 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 */
       };
   #include <time.h>

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

描述

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

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

       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:

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

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

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;
}

回答by pilcrow

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

除了usleep之外,带有 NULL 文件描述符集的不起眼的select将让您以微秒的精度暂停,并且不会出现SIGALRM并发症的风险。

sigtimedwait and sigwaitinfooffer similar behavior.

sigtimedwait 和 sigwaitinfo提供类似的行为。

回答by pilcrow

#include <unistd.h>

int usleep(useconds_t useconds); //pass in microseconds

回答by Jonathan Leffler

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():

作为usleep()POSIX 2008 中未定义的替代方案(尽管它在 POSIX 2004 之前已定义,并且显然可以在 Linux 和其他具有 POSIX 合规历史的平台上使用),POSIX 2008 标准定义了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 rqtpargument 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.

nanosleep- 高分辨率睡眠

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

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

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

回答by Bernardo Ramos

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
    usleep(milliseconds * 1000);
#endif
}

回答by Odin

#include <stdio.h>
#include <stdlib.h>
int main () {

puts("Program Will Sleep For 2 Seconds");

system("sleep 2");      // works for linux systems


return 0;
}