Fix thread-unsafe localtime()

This commit is contained in:
Anon2026
2026-01-07 20:24:59 +03:00
parent ef8f5f1ff5
commit b8a56288be
2 changed files with 17 additions and 3 deletions

View File

@@ -6,6 +6,7 @@
* See full license text in LICENSE file at top of project tree
*/
#include <time.h>
#include <iomanip>
#include <sstream>
#include <thread>
@@ -93,11 +94,16 @@ namespace http {
static std::string ConvertTime (uint64_t time)
{
struct tm caltime;
lldiv_t divTime = lldiv(time, 1000);
time_t t = divTime.quot;
struct tm *tm = localtime(&t);
#ifdef _WIN32
localtime_s(&caltime, &t);
#else
localtime_r(&t, &caltime);
#endif
char date[128];
snprintf(date, sizeof(date), "%02d/%02d/%d %02d:%02d:%02d.%03lld", tm->tm_mday, tm->tm_mon + 1, tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec, divTime.rem);
snprintf(date, sizeof(date), "%02d/%02d/%d %02d:%02d:%02d.%03lld", caltime.tm_mday, caltime.tm_mon + 1, caltime.tm_year + 1900, caltime.tm_hour, caltime.tm_min, caltime.tm_sec, divTime.rem);
return date;
}

View File

@@ -6,6 +6,8 @@
* See full license text in LICENSE file at top of project tree
*/
#include <time.h>
#include "Log.h"
#include "util.h"
@@ -140,8 +142,14 @@ namespace log {
}
const char * Log::TimeAsString(std::time_t t) {
struct tm caltime;
if (t != m_LastTimestamp) {
strftime(m_LastDateTime, sizeof(m_LastDateTime), m_TimeFormat.c_str(), localtime(&t));
#ifdef _WIN32
localtime_s(&caltime, &t);
#else
localtime_r(&t, &caltime);
#endif
strftime(m_LastDateTime, sizeof(m_LastDateTime), m_TimeFormat.c_str(), &caltime);
m_LastTimestamp = t;
}
return m_LastDateTime;