睡在里面循环

时间:2014-09-02 15:54:15

标签: c linux sleep

我无法理解为什么下面的代码会像这样工作......我的意思是:而不是打印"你好"在每一秒延迟之后......它等待5秒钟并立即显示hellohellohellohellohello。

#include <stdio.h>

int i;
for(i=0; i<5; i++) {
   printf("hello");
   sleep(1);
}       

5 个答案:

答案 0 :(得分:11)

如果输出为tty,则printf()stdout)的输出默认为行缓冲。你需要一个

printf("hello\n");

printf("hello");
fflush(stdout);

后者将在每次迭代时显式刷新输出。

答案 1 :(得分:4)

printf不会立即打印,而是每行缓存一行。

添加&#34; \&#34; (换行符)添加字符串printf("hello\n");的结尾或使用写入函数write(STDOUT_FILENO, "hello", sizeof("hello"));

答案 2 :(得分:3)

您正在写入标准输出(stdout),缓冲。如果您希望立即打印内容,可以刷新输出或插入换行符。

您可以在字符串末尾添加\n以打印换行符 - 将printf行更改为:

   printf("hello\n");

stdout之后清除fflush缓冲区电话printf

#include <stdio.h>

int main() {
    int i;
    for(i=0; i<5; i++) {
       printf("hello");
       fflush(stdout);
       sleep(1);
    }       
}

答案 3 :(得分:1)

通常可以缓冲输出。这意味着实现在实际写入控制台之前收集了几个字节。您可以通过fflush(stdout)显式写入缓冲区。对于所有文件描述符都是如此,其中一个是stdout,即终端输出。您可以使用setbuff(stdout,NULL)禁用缓冲,但这在性能方面几乎不是一个好主意。

答案 4 :(得分:0)

试试这个:

int i;
for(i=0;i<5;i++){
printf("hello\n");
i=0;
sleep(1);
}
相关问题