我有一些在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 */ };
更多推荐
发布评论