我希望在C11程序中睡眠。无论是在gcc(4.8.2)还是clang(3.2)的-std=c11
选项下,都没有声明unistd.h
中的usleep
或time.h
中的nanosleep
。
grep sleep /usr/include/*.h
命令没有显示任何其他可能的睡眠函数。
我需要具有至少毫秒精度的睡眠功能。
如何在C11中进行睡眠?
-std=gnu11
代替-std=c11
(clang和gcc通用)。这将导致<time.h>
头文件定义nanosleep
。nanosleep
的方法是,在空文件描述符上调用带有超时的pselect
,但仅适用于-std=gnu11
而不是-std=c11
。#include <stdio.h>
#include <sys/select.h>
int main() // Compile with -std=gnu11 (and not -std=c11)
{
struct timespec ts1 = {
.tv_sec = 0,
.tv_nsec = 500*1000*1000
};
printf("first\n");
nanosleep(&ts1, NULL);
printf("second\n");
pselect(0, NULL, NULL, NULL, &ts1, NULL);
printf("third\n");
}
int thrd_sleep( const struct timespec* time_point, struct timespec* remaining )
<windows.h>
中有一个Sleep函数,在<unistd.h>
中有一个usleep函数。Sleep函数以毫秒为单位,而usleep函数以微秒为单位。usleep
接受微秒为单位的时间 ("u" = "µ")。感谢您在这个老问题中提供了明智的答案。 - Potatoswatter/usr/include/
中进行 grep 的事实可能已经暴露了这一点。 - cdjc
__STDC_NO_THREADS__
,而我所拥有的唯一的threads.h是Linux内核头文件中的一个,显然不是正确的。 - cdjc