project64/Source/Common/Util.cpp

89 lines
2.7 KiB
C++
Raw Normal View History

2015-11-06 11:55:21 +00:00
#include "Util.h"
2021-04-12 09:41:28 +00:00
#include "StdString.h"
#include "path.h"
#ifdef _WIN32
#include <windows.h>
2015-11-06 11:55:21 +00:00
#include <Tlhelp32.h>
#else
#include <time.h>
#endif
2015-11-06 11:55:21 +00:00
void pjutil::Sleep(uint32_t timeout)
{
#ifdef _WIN32
2015-11-06 11:55:21 +00:00
::Sleep(timeout);
#else
int was_error;
struct timespec elapsed, tv;
elapsed.tv_sec = timeout / 1000;
elapsed.tv_nsec = (timeout % 1000) * 1000000;
do {
errno = 0;
tv.tv_sec = elapsed.tv_sec;
tv.tv_nsec = elapsed.tv_nsec;
was_error = nanosleep(&tv, &elapsed);
} while (was_error && (errno == EINTR));
#endif
2015-11-06 11:55:21 +00:00
}
#ifdef _WIN32
2015-11-06 11:55:21 +00:00
bool pjutil::TerminatedExistingExe()
{
bool bTerminated = false;
bool AskedUser = false;
DWORD pid = GetCurrentProcessId();
HANDLE nSearch = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (nSearch != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 lppe;
memset(&lppe, 0, sizeof(PROCESSENTRY32));
lppe.dwSize = sizeof(PROCESSENTRY32);
stdstr ModuleName = CPath(CPath::MODULE_FILE).GetNameExtension();
if (Process32First(nSearch, &lppe))
{
do
{
if (_wcsicmp(lppe.szExeFile, ModuleName.ToUTF16().c_str()) != 0 ||
2015-11-06 11:55:21 +00:00
lppe.th32ProcessID == pid)
{
continue;
}
if (!AskedUser)
{
stdstr_f Message("%s currently running\n\nTerminate PID %d now?", ModuleName.c_str(), lppe.th32ProcessID);
stdstr_f Caption("Terminate %s", ModuleName.c_str());
2015-11-06 11:55:21 +00:00
AskedUser = true;
2021-04-12 11:35:39 +00:00
int res = MessageBox(nullptr, Message.ToUTF16().c_str(), Caption.ToUTF16().c_str(), MB_YESNO | MB_ICONEXCLAMATION);
2015-11-06 11:55:21 +00:00
if (res != IDYES)
{
break;
}
}
HANDLE hHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, lppe.th32ProcessID);
2021-04-12 11:35:39 +00:00
if (hHandle != nullptr)
2015-11-06 11:55:21 +00:00
{
if (TerminateProcess(hHandle, 0))
{
bTerminated = true;
WaitForSingleObject(hHandle, 30 * 1000);
2015-11-06 11:55:21 +00:00
}
else
{
stdstr_f Message("Failed to terminate PID %d", lppe.th32ProcessID);
stdstr_f Caption("Terminate %s failed!", ModuleName.c_str());
2021-04-12 11:35:39 +00:00
MessageBox(nullptr, Message.ToUTF16().c_str(), Caption.ToUTF16().c_str(), MB_YESNO | MB_ICONEXCLAMATION);
2015-11-06 11:55:21 +00:00
}
CloseHandle(hHandle);
}
} while (Process32Next(nSearch, &lppe));
}
CloseHandle(nSearch);
}
return bTerminated;
}
#endif