在C组件中等待语句?

Eri*_*ric 3 c wait

c组件中是否有等待语句?例如,在继续该过程之前等待0.5秒?

谢谢!

Joh*_*iss 7

在POSIX中有

usleep(500);
Run Code Online (Sandbox Code Playgroud)

nanosleep(...);
Run Code Online (Sandbox Code Playgroud)

看看的手动usleep(3)nanosleep(2).编辑:nanosleep现在似乎是要走的路,usleep甚至POSIX.2008根据其手册页被弃用!


unw*_*ind 7

总结并纠正Johannes Weiss的帖子中的一个小问题(非德语键盘,对不起):

在旧式POSIX中,您可以使用usleep()函数,该函数接受作为无符号整数参数休眠的微秒数.因此,要睡半秒钟,你会打电话:

#include <unistd.h>
usleep(500000); /* Five hundred thousand microseconds is half a second. */
Run Code Online (Sandbox Code Playgroud)

对于较新的POSIX风格的程序(我的Gentoo Linux盒子'手册页说它是POSIX.1-2001),你会使用nanosleep(),它需要一个指向一个结构的指针来保持睡眠时间.睡半秒钟看起来像这样:

#include <time.h>
struct timespec t;
t.tv_sec = 0;
t.tv_nsec = 500000000; /* Five hundred million nanoseconds is half a second. */
nanosleep(&t, NULL); /* Ignore remainder. */
Run Code Online (Sandbox Code Playgroud)

nanosleep()的第二个参数称为"rem",如果睡眠以某种方式中断,则接收剩余的时间.为简单起见,我把它留在NULL,这里.你可以做一个循环,直到rem(足够接近)为零,以确保你真正得到你的睡眠,无论任何中断.