From f02333a560f8f61ee4e868118167f996cbd79b0d Mon Sep 17 00:00:00 2001
From: armatusmiles <akurotych@gmail.com>
Date: Thu, 19 Jul 2018 14:57:01 +0300
Subject: [PATCH] Add dap_process_manager

---
 core/dap_process_manager.c | 52 ++++++++++++++++++++++++++++++++++++++
 core/dap_process_manager.h | 22 ++++++++++++++++
 2 files changed, 74 insertions(+)
 create mode 100755 core/dap_process_manager.c
 create mode 100755 core/dap_process_manager.h

diff --git a/core/dap_process_manager.c b/core/dap_process_manager.c
new file mode 100755
index 0000000..a291009
--- /dev/null
+++ b/core/dap_process_manager.c
@@ -0,0 +1,52 @@
+#ifdef __linux__
+#include <stdio.h>
+#include <sys/types.h>
+#include <signal.h>
+
+#include "dap_process_manager.h"
+#include "dap_common.h"
+
+#undef LOG_TAG
+#define LOG_TAG "dap_process_manager"
+
+bool is_process_running(pid_t pid) {
+    return kill(pid, 0) == 0;
+}
+
+bool save_process_pid_in_file(const char* file_path) {
+    FILE * fpid = fopen(file_path, "w");
+    if (fpid == NULL) {
+        log_it(L_ERROR, "Cant create/open file by path %s",file_path);
+        return false;
+    }
+    fprintf(fpid, "%d", getpid());
+    fclose(fpid);
+    return true;
+}
+
+pid_t get_pid_from_file(const char* file_path) {
+    FILE * fpid = fopen(file_path, "r");
+    if (fpid == NULL) {
+        log_it(L_ERROR, "Cant create/open file by path %s",file_path);
+        return false;
+    }
+
+    pid_t f_pid = 0;
+    fscanf(fpid, "%d", &f_pid);
+    fclose(fpid);
+
+    return f_pid;
+}
+
+bool daemonize_process() {
+    return daemon(1,1) == 0;
+}
+
+bool kill_process(pid_t pid) {
+    if (!is_process_running(pid)) {
+        return false;
+    }
+    return kill(pid, SIGKILL) == 0;
+}
+
+#endif
diff --git a/core/dap_process_manager.h b/core/dap_process_manager.h
new file mode 100755
index 0000000..2fb47d8
--- /dev/null
+++ b/core/dap_process_manager.h
@@ -0,0 +1,22 @@
+#ifdef __linux__
+
+#include <stdbool.h>
+#include <unistd.h>
+
+/* Saves process pid into file by file_path.
+ * If file exists he will be overwritten */
+extern bool save_process_pid_in_file(const char* file_path);
+
+/* File must consist only PID. Return 0 if file is clear. */
+extern pid_t get_pid_from_file(const char* file_path);
+
+/* Return true if process running */
+extern bool is_process_running(pid_t pid);
+
+/* Demonizes current process and exit from program */
+extern bool daemonize_process(void);
+
+/* Sends SIGKILL to process */
+extern bool kill_process(pid_t pid);
+
+#endif
-- 
GitLab