From b97db529be365851633a6cc1c9285d930209049d Mon Sep 17 00:00:00 2001 From: Jan200101 Date: Sun, 22 Jan 2023 02:56:48 +0100 Subject: hook stash: a1af9ba65d57be898e079a98229845f42069c1e6 --- src/proc.c | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/proc.c (limited to 'src/proc.c') diff --git a/src/proc.c b/src/proc.c new file mode 100644 index 0000000..2d74a1f --- /dev/null +++ b/src/proc.c @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#endif + +#include "proc.h" + +pid_t getPid(const char* process_name) +{ +#if defined(__linux__) || defined(__FreeBSD__) + +#ifdef __FreeBSD__ + // on FreeBSD /proc is not mounted by default + if (!isDir("/proc")) + return -1; +#endif + + pid_t pid; + char buf[PATH_MAX]; + struct dirent* ent; + DIR* proc = opendir("/proc"); + FILE* stat; + + if (proc) + { + while ((ent = readdir(proc)) != NULL) + { + long lpid = atol(ent->d_name); + if (!lpid) continue; + + snprintf(buf, sizeof(buf), "/proc/%ld/stat", lpid); + stat = fopen(buf, "r"); + + if (stat && (fscanf(stat, "%i (%[^)])", &pid, buf)) == 2) + { + if (!strcmp(buf, process_name)) + { + fclose(stat); + closedir(proc); + return pid; + } + fclose(stat); + } + } + + closedir(proc); + } + +#elif _WIN32 + HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + PROCESSENTRY32 pe32 = {0}; + pe32.dwSize = sizeof(PROCESSENTRY32); + Process32First(hSnap,&pe32); + + while(Process32Next(hSnap,&pe32)) + { + if (!strcmp(pe32.szExeFile, process_name)) + return (long)pe32.th32ProcessID; + } +#else + #error No Implementation +#endif + return -1; +} -- cgit v1.2.3