c - C 到毫秒是否有替代 sleep 功能?

标签 c linux sleep

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

源代码已包含<windows.h>头文件,程序员使用了Sleep()函数等待几毫秒。这不适用于 Linux。

但是,我可以使用 sleep(seconds)函数,但它以秒为单位使用整数。我不想将毫秒转换为秒。我可以在 Linux 上使用 gcc 编译的替代 sleep 功能吗?

最佳答案

是 - 较旧 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.

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


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

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

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

关于c - C 到毫秒是否有替代 sleep 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1157209/

相关文章:

在 C (GCC) 中对宽字符字符串调用 goto

C 有关文件的统计信息,

Docker 容器中的 MySQL

linux - tftp: 服务器错误: (2) 访问冲突

c - 是否有某种命令可以在程序中创建延迟

bash - sleep 后如何使用 Heredoc 发送一些输入?

c++ - 为什么函数指针和数据指针在C/C++中不兼容?

linux - 加载共享库时出错 (glew)

android - 更改按钮和 sleep 的背景

c - 数据设计: better to nest structures or pointers to structures?