]> git.stg.codes - stg.git/blob - stglibs/scriptexecuter.lib/scriptexecuter.c
Keep stglibs headers and libraries "at home"
[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 #ifdef LINUX
44 void Executer(int msgID, pid_t pid, char * procName)
45 #else
46 void Executer(int msgID, pid_t pid)
47 #endif
48 {
49 msgid = msgID;
50 if (pid)
51     return;
52 nonstop = 1;
53
54 #ifdef LINUX
55 memset(procName, 0, strlen(procName));
56 strcpy(procName, "stg-exec");
57 #else
58 setproctitle("stg-exec");
59 #endif
60
61 struct sigaction newsa, oldsa;
62 sigset_t sigmask;
63
64 sigemptyset(&sigmask);
65 sigaddset(&sigmask, SIGTERM);
66 newsa.sa_handler = SIG_IGN;
67 newsa.sa_mask = sigmask;
68 newsa.sa_flags = 0;
69 sigaction(SIGTERM, &newsa, &oldsa);
70
71 sigemptyset(&sigmask);
72 sigaddset(&sigmask, SIGINT);
73 newsa.sa_handler = SIG_IGN;
74 newsa.sa_mask = sigmask;
75 newsa.sa_flags = 0;
76 sigaction(SIGINT, &newsa, &oldsa);
77
78 sigemptyset(&sigmask);
79 sigaddset(&sigmask, SIGHUP);
80 newsa.sa_handler = SIG_IGN;
81 newsa.sa_mask = sigmask;
82 newsa.sa_flags = 0;
83 sigaction(SIGHUP, &newsa, &oldsa);
84
85 sigemptyset(&sigmask);
86 sigaddset(&sigmask, SIGUSR1);
87 newsa.sa_handler = CatchUSR1Executer;
88 newsa.sa_mask = sigmask;
89 newsa.sa_flags = 0;
90 sigaction(SIGUSR1, &newsa, &oldsa);
91
92 int ret;
93
94 struct SCRIPT_DATA sd;
95
96 while (nonstop)
97     {
98     sd.mtype = 1;
99     ret = msgrcv(msgid, &sd, MAX_SCRIPT_LEN, 0, 0);
100
101     if (ret < 0)
102         {
103         usleep(20000);
104         continue;
105         }
106     int ret = system(sd.script);
107     if (ret == -1)
108         {
109         // Fork failed
110         }
111     }
112 }
113 //-----------------------------------------------------------------------------