usleep() 函数不允许循环继续

发布于 2024-08-20 23:42:30 字数 480 浏览 3 评论 0原文

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

带刺的爱情 2024-08-27 23:42:30

您的输出缓冲区没有被刷新。默认情况下,当流中出现新行时写入输出。将 printf 更改为:

printf("%d\n", i);

或尝试以下操作:

printf("%d", i);
fflush(stdout);

另外,如果您想删除行缓冲行为,可以使用 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:

printf("%d\n", i);

or try this:

printf("%d", i);
fflush(stdout);

Also, if you want to remove the line-buffering behaviour, you can use setvbuf() and the _IONBUF mode.

就是爱搞怪 2024-08-27 23:42:30

旁白 - 要将 1 秒传递给 usleep,请调用 usleep(1000000)

Aside - To pass 1 sec to usleep, call usleep(1000000)

献世佛 2024-08-27 23:42:30

在每个 printf 之后调用 fflush(stdout) 来刷新缓冲的输出

call fflush(stdout) after each printf to flush the buffered output

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文