From 2a82c1e72badb44b4492ca808fcec363a5f81aeb Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Fri, 4 Mar 2022 06:40:28 +0100 Subject: [PATCH] Lock standard output when composing log message (#15798) Single log message is created by calling printf function multiple number of times. In case of using log subsystem from more than one thread, the log message might be corrupted. In order to prevent that, it is advised to use flockfile()/funlockfile() for given stream. --- src/platform/Linux/Logging.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/platform/Linux/Logging.cpp b/src/platform/Linux/Logging.cpp index 5f8aeb57e73575..48ee96ef83da06 100644 --- a/src/platform/Linux/Logging.cpp +++ b/src/platform/Linux/Logging.cpp @@ -37,12 +37,18 @@ void ENFORCE_FORMAT(3, 0) LogV(const char * module, uint8_t category, const char // indicate the error occurred during getting time. gettimeofday(&tv, nullptr); + // Lock standard output, so a single log line will not be corrupted in case + // where multiple threads are using logging subsystem at the same time. + flockfile(stdout); + printf("[%" PRIu64 ".%06" PRIu64 "][%lld:%lld] CHIP:%s: ", static_cast(tv.tv_sec), static_cast(tv.tv_usec), static_cast(syscall(SYS_getpid)), static_cast(syscall(SYS_gettid)), module); vprintf(msg, v); printf("\n"); fflush(stdout); + funlockfile(stdout); + // Let the application know that a log message has been emitted. DeviceLayer::OnLogOutput(); }