我正在运行一个套接字应用程序,它可以监听实时数据并持续处理它。我有一段独立的代码,应该每秒执行一次。但是这段代码没有执行。让我用以下代码澄清:
在main.cpp中,我有
Client client;
//Code to connect to socket and subscribe to realtime data.
while(client.isConnected){
client.executeRealTime();
}
在Client.cpp中,我有以下代码:
void Client::executeRealTime(){
time_t now = time(NULL);
int currSeconds=now%86400;
if(currSeconds>13800){
printf("Before Condition %d %d\n",currSeconds,strategyTimer);
if(currSeconds>strategyTimer){
printf("After Condition %d %d\n",currSeconds,strategyTimer);
for(int i=0;i<numStrategies;i++){
if((strategies[i]->isTradeable)==1){
strategies[i]->execute(currSeconds);
}
}
strategyTimer=currSeconds;
}
}
}
变量strategyTimer的类型为int,并且不会在代码中的任何其他位置访问它。
代码在条件&#34;之前打印出&#34;的printf;当它运行时不断。我可以从输出中验证每一秒都会出现一个print语句,其中currSeconds大于strategyTimer的1,然后是&#34;在条件&#34;之后的print语句。然后我在条件&#34;之前注释掉了#34; print语句并再次运行代码。这次我希望打印声明&#34; After Condition&#34;每秒跑一次。但该声明从未打印过。除非代码进入内部&#34;如果&#34;块,strategyTimer变量无法更改。我不明白为什么在条件之前有&#34;&#34; print语句正在改变&#34;条件后的行为&#34;打印声明。
请让我了解如何解决这个问题。
我在Windows 7中使用eclipse工作区并使用cygwin工具链进行编译。
Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20199 20198
After Condition 20199 20198
Before Condition 20199 20199
Before Condition 20199 20199
Before Condition 20199 20199
但是当我注释掉Before Condition语句时,我看不到任何输出。
答案 0 :(得分:2)
正如我在20多年前调试c程序时发现的,printf
将事物放入stdout的缓冲区。但是stdout没有义务将它真正地放到你的屏幕上。它会在准备就绪时这样做。
这会产生令人讨厌的效果,让你在错误的地方找到你的错误。
正如Flushing buffers in C中指出的那样,解决方案是在调试fflush
语句后使用printf
,或使用不受此限制的其他日志记录机制