C11中的睡眠功能

cdj*_*djc 7 c sleep c11

我想睡在C11程序中.usleep(在unistd.h中)和nanosleep(在time.h中)都没有声明-std=c11gcc(4.8.2)和clang(3.2).

A grep sleep /usr/include/*.h没有透露任何其他可能的睡眠候选人.

我需要一个至少毫秒精度的睡眠.

我怎么在C11睡觉?

cdj*_*djc 6

使用-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");
}
Run Code Online (Sandbox Code Playgroud)