From 917917f8d15e9d91e41965f7221680254633175e Mon Sep 17 00:00:00 2001 From: Gaspar Capello Date: Tue, 26 Dec 2023 16:56:23 -0300 Subject: [PATCH] Fix 'is_process_running' returns an incorrect 'true' when process 'pid' exists, but whose process does not belong to the current application. Effect on Aseprite: some recovery sessions do not appear in the Recovery menu. --- base/process.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++++++-- base/process.h | 3 +++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/base/process.cpp b/base/process.cpp index 887f2d475..855e8de3d 100644 --- a/base/process.cpp +++ b/base/process.cpp @@ -1,5 +1,5 @@ // LAF Base Library -// Copyright (c) 2021 Igara Studio S.A. +// Copyright (c) 2021-2024 Igara Studio S.A. // Copyright (c) 2015-2016 David Capello // // This file is released under the terms of the MIT license. @@ -13,12 +13,19 @@ #if LAF_WINDOWS #include + #include + #include #else #include #include #include #endif +#if LAF_MACOS + #include + #include +#endif + namespace base { #if LAF_WINDOWS @@ -28,6 +35,33 @@ pid get_current_process_id() return (pid)GetCurrentProcessId(); } +bool is_process_running(pid pid, const char* pname) +{ + bool running = false; + HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0); + if (handle) { + PROCESSENTRY32 pe; + pe.dwSize = sizeof(PROCESSENTRY32); + if (Process32First(handle, &pe)) { + do { + char buf[64]; + wcstombs(buf, pe.szExeFile, 64); + std::string str(buf); + for (char& c : str) { + c = tolower(c); + } + if (pe.th32ProcessID == pid && + str == pname) { + running = true; + } + } while (Process32Next(handle, &pe)); + } + CloseHandle(handle); + } + + return running; +} + bool is_process_running(pid pid) { bool running = false; @@ -44,18 +78,43 @@ bool is_process_running(pid pid) return running; } -#else // !LAF_WINDOWS +#elif LAF_MACOS pid get_current_process_id() { return (pid)getpid(); } +bool is_process_running(pid pid, const char* pname) +{ + struct proc_bsdinfo process; + proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, + &process, PROC_PIDTBSDINFO_SIZE); + return (strcmp(pname, process.pbi_name) == 0); +} + bool is_process_running(pid pid) { return (kill(pid, 0) == 0); } +#elif LAF_LINUX + +pid get_current_process_id() +{ + return (pid)getpid(); +} + +bool is_process_running(pid pid, const char* pname) +{ + return (kill(pid, 0) == 0); +} + +bool is_process_running(pid pid) +{ + return is_process_running(pid, ""); +} + #endif } // namespace base diff --git a/base/process.h b/base/process.h index 445b87cd6..3c4e4058f 100644 --- a/base/process.h +++ b/base/process.h @@ -1,4 +1,5 @@ // LAF Base Library +// Copyright (c) 2023-2024 Igara Studio S.A. // Copyright (c) 2015-2016 David Capello // // This file is released under the terms of the MIT license. @@ -16,6 +17,8 @@ namespace base { pid get_current_process_id(); + bool is_process_running(pid pid, const char* pname); + bool is_process_running(pid pid); } // namespace base