I have created a server program, and a certain error has occurred twice where the function ‘clock()’ has returned a negative value (and crashed the server). Both times it occurred when the program had been running for more than 100 hours, on a Windows 32-bit VPS.
Here’s the setup I have in main.cpp (cut where appropriate):
while (1) {
Sleep(STEP);
//execute main code like connection handling, AI, etc.
//check for clock error
if (clock() < 0) {
//error saved here
//close server
return 0;
}
}
That’s it, pretty simple. clock() is used throughout the rest of the program extensively, so when it glitches up like this it causes a lot of problems.
I am wondering, why does it return a negative value, and how can I fix it?
Thanks.
According to Microsoft’s documentation it can return -1 if “the amount of elapsed time is unavailable”. Unfortunately they don’t explain how the time would be unavailable.
The definition of
clock_tislongwhich is a 32-bit signed value – it can hold 2**31 before it overflows. The value ofCLOCKS_PER_SECONDis 1000, so it should be good for 596 hours.