Add mbtk_servicesd
Change-Id: Ie2dcb3420468035f2a2089ac967ab3c1ccb3bf1a
diff --git a/mbtk/mbtk_servicesd/instance_monitor_service.c b/mbtk/mbtk_servicesd/instance_monitor_service.c
new file mode 100755
index 0000000..2557304
--- /dev/null
+++ b/mbtk/mbtk_servicesd/instance_monitor_service.c
@@ -0,0 +1,106 @@
+/*
+* instance_monitor_service.c
+*
+* $file_describe$
+*
+*/
+/******************************************************************************
+
+ EDIT HISTORY FOR FILE
+
+ WHEN WHO WHAT,WHERE,WHY
+-------- -------- -------------------------------------------------------
+2024/6/12 LiuBin Initial version
+
+******************************************************************************/
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+#include <pthread.h>
+
+#include "instance_info.h"
+#include "mbtk_log.h"
+#include "mbtk_utils.h"
+
+#define INS_MONITOR_INTERVAL 3 // s
+
+int instance_info_size = 0;
+instance_info_t instance_infos[INSTANCE_NUM_MAX] = {0};
+
+static void program_start(instance_info_t *info)
+{
+ LOGD("Will start program : %s", info->ins_name);
+ system(info->ins_cmd);
+}
+
+static int pidof(const char *program)
+{
+ char buff[128] = {0};
+ char cmd[128] = {0};
+ snprintf(cmd, sizeof(cmd), "pidof %s", program);
+ if(mbtk_cmd_line(cmd, buff, sizeof(buff)) && strlen(buff)) {
+ int pid = atoi(buff);
+ if(pid > 0) {
+ return pid;
+ } else {
+ return -1;
+ }
+ }
+ return -1;
+}
+
+static void* ins_monitor_service_run(void *arg)
+{
+ int i = 0;
+ LOGD("Will monitor program:");
+ while(i < instance_info_size) {
+ LOGD("%s:%s", instance_infos[i].ins_name, instance_infos[i].ins_cmd);
+ if(instance_infos[i].ins_pid < 0) {
+ instance_infos[i].ins_pid = pidof(instance_infos[i].ins_name);
+ }
+
+ if(instance_infos[i].ins_pid < 0) {
+ LOGE("%s has not running,will not monitor...", instance_infos[i].ins_name);
+ }
+ i++;
+ }
+
+ while(1) {
+ sleep(INS_MONITOR_INTERVAL);
+ i = 0;
+ while(i < instance_info_size) {
+ if(instance_infos[i].ins_pid > 0) {
+ int pid = pidof(instance_infos[i].ins_name);
+ if(pid > 0) {
+ // Programe is running, do nothing.
+ } else {
+ program_start(instance_infos + i);
+ }
+ }
+ i++;
+ }
+ }
+
+ return NULL;
+}
+
+int ins_monitor_service_start()
+{
+ pthread_t pid;
+ pthread_attr_t thread_attr;
+ pthread_attr_init(&thread_attr);
+ if(pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED))
+ {
+ LOGE("pthread_attr_setdetachstate() fail.");
+ return -1;
+ }
+
+ if(pthread_create(&pid, &thread_attr, ins_monitor_service_run, NULL))
+ {
+ LOGE("pthread_create() fail.");
+ return -1;
+ }
+
+ return 0;
+}