Reputation: 525
I am running a socket application which listens to realtime data and processes it continuously. I have separate piece of code which is supposed to execute every second. But that piece of code does not execute. Let me clarify with the code as follows:
In main.cpp, I have
Client client;
//Code to connect to socket and subscribe to realtime data.
while(client.isConnected){
client.executeRealTime();
}
In Client.cpp, I have the following piece of code:
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;
}
}
}
Variable strategyTimer is of type int and it is not accessed anywhere else in the code.
The code prints out the printf of "before Condition" continously when it is run. I can verify from the output that at each second, there occurs a print statement where currSeconds is more than strategyTimer by 1 followed by print statement of "after condition". Then I comment out the "before condition" print statement and run the code again. This time I expect the print statement "After Condition" to run every second. But that statement is never printed. Unless the code enters the inner "if" block, the strategyTimer variable cannot be changed. I do not understand why having the "before condition" print statement is changing the behaviour of "after condition" print statement.
Please let me understand how to fix this.
I am using eclipse workspace in windows 7 and compiling using cygwin toolchain.
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
But when I comment out the Before Condition statement, I do not see any output.
Upvotes: 0
Views: 1091
Reputation: 1322
As I discovered while debugging c programs over 20 years ago, printf
puts things into stdout's buffer. But stdout is under no obligation to actually put that to your screen. It will do so when it's ready.
This has the nasty effect of making you look in entirely the wrong place for your bugs.
The solution, as is pointed out in Flushing buffers in C is to use fflush
after your debug printf
statements, or to use a different logging mechanism that doesn't suffer from this.
Upvotes: 2