From d0374812e403ddf6d46f404602c2d3e188595629 Mon Sep 17 00:00:00 2001 From: Thulinma Date: Fri, 19 Jan 2024 15:53:10 +0100 Subject: [PATCH] Prevent race condition when grim_reaper thread is already trying to lock while the thread is being asked to shut down --- lib/procs.cpp | 46 ++++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/lib/procs.cpp b/lib/procs.cpp index 5b81bd54..ebf2d56a 100644 --- a/lib/procs.cpp +++ b/lib/procs.cpp @@ -199,29 +199,31 @@ void Util::Procs::grim_reaper(void *n){ VERYHIGH_MSG("Grim reaper start"); while (thread_handler){ { - tthread::lock_guard guard(plistMutex); - int status; - pid_t ret = -1; - while (ret != 0){ - ret = waitpid(-1, &status, WNOHANG); - if (ret <= 0){// ignore, would block otherwise - if (ret == 0 || errno != EINTR){break;} - continue; - } - int exitcode; - if (WIFEXITED(status)){ - exitcode = WEXITSTATUS(status); - }else if (WIFSIGNALED(status)){ - exitcode = -WTERMSIG(status); - }else{// not possible - break; - } - if (plist.count(ret)){ - HIGH_MSG("Process %d fully terminated with code %d", ret, exitcode); - plist.erase(ret); - }else{ - HIGH_MSG("Child process %d exited with code %d", ret, exitcode); + if (plistMutex.try_lock()){ + int status; + pid_t ret = -1; + while (ret != 0){ + ret = waitpid(-1, &status, WNOHANG); + if (ret <= 0){// ignore, would block otherwise + if (ret == 0 || errno != EINTR){break;} + continue; + } + int exitcode; + if (WIFEXITED(status)){ + exitcode = WEXITSTATUS(status); + }else if (WIFSIGNALED(status)){ + exitcode = -WTERMSIG(status); + }else{// not possible + break; + } + if (plist.count(ret)){ + HIGH_MSG("Process %d fully terminated with code %d", ret, exitcode); + plist.erase(ret); + }else{ + HIGH_MSG("Child process %d exited with code %d", ret, exitcode); + } } + plistMutex.unlock(); } } Util::sleep(500);