usleep() 函数不允许循环继续
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int i=0;
while(i<10)
{
printf("%d", i);
usleep(10000); // or sleep(1)
i++;
}
return 0;
}
我希望程序持续 10 秒,即打印 1 - 等待 1 秒 - 打印 2 - 等待 1 秒,依此类推,直到结束。但它并没有这样做——它只是一直等待(10秒),然后一起打印整个数字数组,它们之间没有任何时间延迟,它只是立即打印0123456789。 编辑:我尝试使用 sleep() 而不是 usleep 但它是相同的 如何修复它?为什么会这样?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int i=0;
while(i<10)
{
printf("%d", i);
usleep(10000); // or sleep(1)
i++;
}
return 0;
}
I want the program to last 10 secs, i.e. print 1 - wait 1 sec - print 2 - wait 1 sec and so on until the end. But it doesn't do that - it just waits for all the time (10 secs) and then prints the whole array of numbers together without any time delays between them, it just prints 0123456789 at once.
EDIT: I tried with sleep() instead of usleep but it's the same
How to fix it ? And why it's like that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的输出缓冲区没有被刷新。默认情况下,当流中出现新行时写入输出。将
printf
更改为:或尝试以下操作:
另外,如果您想删除行缓冲行为,可以使用
setvbuf()
和_IONBUF
模式。Your output buffer is not being flushed. By default, output is written when a new line appears in the stream. Change your
printf
to this:or try this:
Also, if you want to remove the line-buffering behaviour, you can use
setvbuf()
and the_IONBUF
mode.旁白 - 要将 1 秒传递给
usleep
,请调用usleep(1000000)
Aside - To pass 1 sec to
usleep
, callusleep(1000000)
在每个 printf 之后调用 fflush(stdout) 来刷新缓冲的输出
call
fflush(stdout)
after each printf to flush the buffered output