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