睡眠功能在linux中的c疯狂bug

时间:2014-06-10 08:15:28

标签: c linux

我有这个简单的代码“ int中的printinterval

sleep(printinterval/3);
displayPrint();  //// just some printing func
sleep(printinterval/3);
displayPrint(); 
sleep(printinterval-2*(int)(printinterval/3));
displayPrint(); 

问题是它不能以正确的方式做延迟, 跳过1次睡眠

但是

sleep(printinterval/3);
printf("\n");
displayPrint();  //// just some printing func
printf("\n");    
sleep(printinterval/3);
printf("\n");    
displayPrint();
printf("\n"); 
sleep(printinterval-2*(int)(printinterval/3));
printf("\n");
displayPrint(); 

就像一个魅力

任何想法? thx:)

EDITED: thx的帮助 发现这种方法来解决它

fflush(stdout); // Will now print everything in the stdout buffer

再次,thx

1 个答案:

答案 0 :(得分:9)

流被缓冲,并在遇到\n时刷新。

请参阅:Why does printf not flush after the call unless a newline is in the format string?