c - C 到毫秒是否有替代 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;
}

https://stackoverflow.com/questions/1157209/

相关文章:

linux - 如何来回反向搜索?

linux - 如何在 Linux 上使用 grep 搜索包含 DOS 行尾 (CRLF) 的文件?

linux - 什么进程正在使用我所有的磁盘 IO

python - 在调用者线程中捕获线程的异常?

python - 计算列表差异

linux - 重命名文件和目录(添加前缀)

python - BeautifulSoup 获取 href

linux - Apache VirtualHost 403 被禁止

linux - 如何找到某个命令的目录?

python - 在python中通过分隔符拆分字符串