在C到毫秒中有替代睡眠功能吗?(Is there an alternative sleep function in C to milliseconds?)

编程入门 行业动态 更新时间:2024-10-23 07:39:45
在C到毫秒中有替代睡眠功能吗?(Is there an alternative sleep function in C to milliseconds?)

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

源代码包含了<windows.h>头文件,程序员使用了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?

最满意答案

是 - 较老的POSIX标准定义了usleep() ,所以这在Linux上是可用的:

int usleep(useconds_t usec);

描述

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

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


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

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

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

更多推荐

本文发布于:2023-07-30 22:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中有   睡眠   功能   alternative   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!