aboutsummaryrefslogtreecommitdiff
path: root/src/proc.c
diff options
context:
space:
mode:
authorJan200101 <sentrycraft123@gmail.com>2023-01-22 02:56:48 +0100
committerJan200101 <sentrycraft123@gmail.com>2023-08-05 22:15:10 +0200
commitb97db529be365851633a6cc1c9285d930209049d (patch)
tree7a73d6adf71797b9308692a03253d15d3703b5a8 /src/proc.c
parent045e16665a55e2b7b6dc2e953c91f2125f61e083 (diff)
downloadOFQT-hook.tar.gz
OFQT-hook.zip
hook stash: a1af9ba65d57be898e079a98229845f42069c1e6hook
Diffstat (limited to 'src/proc.c')
-rw-r--r--src/proc.c71
1 files changed, 71 insertions, 0 deletions
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 <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <stdio.h>
+
+#ifdef _WIN32
+#include <windows.h>
+#include <tlhelp32.h>
+#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;
+}