From 532d6b3ac9ca2248a4076135a4a58235040316c8 Mon Sep 17 00:00:00 2001 From: Thomas Jarosch Date: Mon, 17 Oct 2011 11:40:18 +0200 Subject: [PATCH] Replace localtime() with thread safe localtime_r() --- src/logfunc.cpp | 6 +++++- src/timefunc.cpp | 6 ++++-- test/test_timefunc.cpp | 7 +++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/logfunc.cpp b/src/logfunc.cpp index dc49388..115bf03 100644 --- a/src/logfunc.cpp +++ b/src/logfunc.cpp @@ -231,7 +231,11 @@ void log_msg( int level, const std::string& msg) { time_t t = time(NULL); char buffer[32]; - std::strftime(buffer, sizeof(buffer),"%b %d %H:%M:%S ", std::localtime(&t)); + struct tm ta; + if (localtime_r(&t, &ta) == NULL) + memset(&ta, 0, sizeof(struct tm)); + + std::strftime(buffer, sizeof(buffer),"%b %d %H:%M:%S ", &ta); ostr << buffer; } ostr << get_level_tag(level) << " "; diff --git a/src/timefunc.cpp b/src/timefunc.cpp index a45f00e..ab5f6dc 100644 --- a/src/timefunc.cpp +++ b/src/timefunc.cpp @@ -133,9 +133,11 @@ string format_full_time(int seconds) { char buf[50]; memset (buf, 0, 50); - struct tm *ta = localtime ((time_t *)&seconds); + struct tm ta; + if (localtime_r((time_t *)&seconds, &ta) == NULL) + memset (&ta, 0, sizeof(struct tm)); - strftime (buf, 49, "%d.%m.%Y %H:%M", ta); + strftime (buf, 49, "%d.%m.%Y %H:%M", &ta); return string(buf); } diff --git a/test/test_timefunc.cpp b/test/test_timefunc.cpp index 4a2a04e..f4bc4f2 100644 --- a/test/test_timefunc.cpp +++ b/test/test_timefunc.cpp @@ -442,4 +442,11 @@ BOOST_AUTO_TEST_CASE(WeekDisplayString13) BOOST_CHECK_EQUAL(string("Mon-Wed"), week.get_displaystring()); } +BOOST_AUTO_TEST_CASE(FormatFullTime) +{ + time_t seconds = 1318844005; + + BOOST_CHECK_EQUAL("17.10.2011 11:33", format_full_time(seconds)); +} + BOOST_AUTO_TEST_SUITE_END() -- 1.7.1