简体   繁体   English

为什么这个小的C程序不能按预期工作?

[英]Why doesn't this small C program work as expected?

I've got a small C program that makes use of difftime. 我有一个使用difftime的小型C程序。 its really strange, it doesn't print out the line after 10 seconds. 真的很奇怪,它在10秒后没有打印出来。

If however I uncomment out the sleep line then it works. 但是,如果我取消注释睡眠线,那么它将起作用。

Any ideas why this is happening? 任何想法为什么会这样?

/* difftime example */
#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, difftime, time, mktime */

int main ()
{
  time_t start, stop;

start = time(NULL);
        for(; /* some condition that takes forever to meet */;) {
        // do stuff that apparently takes forever.
                stop = time(NULL);
                double diff = difftime(stop, start);
                //sleep (1);
                if (diff >= 10) {
                        printf("10 seconds passed...");
                        start = time(NULL);
                }
        }
}

BTW: Code compiles fine and I'm running it on the Raspberry Pi. 顺便说一句:代码可以很好地编译,我正在Raspberry Pi上运行它。 3.6.11+ #474 PREEMPT Thu Jun 13 17:14:42 BST 2013 armv6l GNU/Linux 3.6.11+#474 PREEMPT周四13月13日17:14:42 BST 2013 armv6l GNU / Linux

Console IO might be line buffered. 控制台IO可能是行缓冲的。 Try flushing 尝试冲洗

printf("10 seconds passed...");
fflush(stdout)

or adding a newline \\n 或添加换行符\\n

printf("10 seconds passed...\n");

I can't reproduce any change in behaviour when the call to sleep is uncommented. 如果没有评论sleep呼叫,我将无法重蹈覆辙。

printf("10 seconds passed...\n");

For sleep(), you need to include unistd.h, as well as adding a newline as others have pointed out. 对于sleep(),您需要包含unistd.h,并添加其他人指出的换行符。

#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, difftime, time, mktime */
#include <unistd.h>     /* sleep() */

If your code compiled without warnings and without including unistd.h, you need to crank your warnings up. 如果您的代码编译时没有警告,也没有包含unistd.h,则需要提高警告程度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM