]> git.stg.codes - stg.git/blob - stglibs/scriptexecuter.lib/scriptexecuter.c
scriptexecuter become a plain C library
[stg.git] / stglibs / scriptexecuter.lib / scriptexecuter.c
1 #include <sys/types.h>
2 #include <sys/ipc.h>
3 #include <sys/msg.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6
7 #include <string.h>
8 #include <errno.h>
9 #include <signal.h>
10
11 #include "scriptexecuter.h"
12
13
14 #define MAX_SCRIPT_LEN  (1100)
15
16 static int msgid;
17 static int nonstop;
18
19 //-----------------------------------------------------------------------------
20 struct SCRIPT_DATA
21 {
22     long    mtype;
23     char    script[MAX_SCRIPT_LEN];
24 } sd;
25 //-----------------------------------------------------------------------------
26 static void CatchUSR1Executer()
27 {
28 nonstop = 0;
29 }
30 //-----------------------------------------------------------------------------
31 int ScriptExec(const char * str)
32 {
33 if (strlen(str) >= MAX_SCRIPT_LEN)
34     return -1;
35
36 strncpy(sd.script, str, MAX_SCRIPT_LEN);
37 sd.mtype = 1;
38 if (msgsnd(msgid, (void *)&sd, MAX_SCRIPT_LEN, 0) < 0)
39     return -1;
40
41 return 0;
42 }
43 //-----------------------------------------------------------------------------
44 #ifdef LINUX
45 void Executer(int msgID, pid_t pid, char * procName)
46 #else
47 void Executer(int msgID, pid_t pid)
48 #endif
49 {
50 msgid = msgID;
51 if (pid)
52     return;
53 nonstop = 1;
54
55 #ifdef LINUX
56 memset(procName, 0, strlen(procName));
57 strcpy(procName, "stg-exec");
58 #else
59 setproctitle("stg-exec");
60 #endif
61
62 struct sigaction newsa, oldsa;
63 sigset_t sigmask;
64
65 sigemptyset(&sigmask);
66 sigaddset(&sigmask, SIGTERM);
67 newsa.sa_handler = SIG_IGN;
68 newsa.sa_mask = sigmask;
69 newsa.sa_flags = 0;
70 sigaction(SIGTERM, &newsa, &oldsa);
71
72 sigemptyset(&sigmask);
73 sigaddset(&sigmask, SIGINT);
74 newsa.sa_handler = SIG_IGN;
75 newsa.sa_mask = sigmask;
76 newsa.sa_flags = 0;
77 sigaction(SIGINT, &newsa, &oldsa);
78
79 sigemptyset(&sigmask);
80 sigaddset(&sigmask, SIGHUP);
81 newsa.sa_handler = SIG_IGN;
82 newsa.sa_mask = sigmask;
83 newsa.sa_flags = 0;
84 sigaction(SIGHUP, &newsa, &oldsa);
85
86 sigemptyset(&sigmask);
87 sigaddset(&sigmask, SIGUSR1);
88 newsa.sa_handler = CatchUSR1Executer;
89 newsa.sa_mask = sigmask;
90 newsa.sa_flags = 0;
91 sigaction(SIGUSR1, &newsa, &oldsa);
92
93 int ret;
94
95 struct SCRIPT_DATA sd;
96
97 while (nonstop)
98     {
99     sd.mtype = 1;
100     ret = msgrcv(msgid, &sd, MAX_SCRIPT_LEN, 0, 0);
101
102     if (ret < 0)
103         {
104         usleep(20000);
105         continue;
106         }
107     int ret = system(sd.script);
108     if (ret == -1)
109         {
110         // Fork failed
111         }
112     }
113 }
114 //-----------------------------------------------------------------------------