5ea1591611a6dbab3f631a3018c978a4e4c4ef1c
[progcomp2012.git] / judge / manager / program.cpp
1 #include <sstream>
2
3 #include <stdarg.h>
4
5 #include <cassert>
6
7 #include "thread_util.h"
8 #include "program.h"
9 #include <vector>
10 #include <string.h>
11 #include <stdio.h>
12
13 #include <stdio.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17
18
19 using namespace std;
20
21
22 /**
23  * Constructor
24  * @param executablePath - path to the program that will be run
25  *
26  * Creates two pipes - one for each direction between the parent process and the AI program
27  * Forks the process. 
28  *      The child process closes unused sides of the pipe, and then calls exec to replace itself with the AI program
29  *      The parent process closes unused sides of the pipe, and sets up member variables - associates streams with the pipe fd's for convenience.
30  */
31 Program::Program(const char * executablePath) : input(NULL), output(NULL), pid(0), paused(false)
32 {
33         
34                 
35         
36         vector<char*> args;
37         if (executablePath[0] != '"')
38                 args.push_back((char*)executablePath);
39         else
40                 args.push_back((char*)(executablePath)+1);
41         char * token = NULL;
42         do
43         {
44                 token = strstr(args[args.size()-1], " ");
45                 if (token == NULL)
46                         break;
47
48                 *token = '\0';
49                 do
50                 {
51                         ++token;
52                         if (*token == '"')
53                                 *token = '\0';
54                 }
55                 while (*token != '\0' && iswspace(*token));
56
57                 if (*token != '\0' && !iswspace(*token))
58                 {
59                         args.push_back(token);
60                 }
61                 else
62                         break;
63         }
64         while (token != NULL);
65
66         char **  arguments = NULL;
67         if (args.size() > 0)
68         {
69                 arguments = new char*[args.size()];
70                 for (unsigned int i=0; i < args.size(); ++i)
71                         arguments[i] = args[i];
72         }
73         //See if file exists and is executable...
74         if (access(executablePath, X_OK) != 0)
75         {
76                 pid = -1;
77                 return;
78         }
79         
80         int readPipe[2]; int writePipe[2];
81         assert(pipe(readPipe) == 0);
82         assert(pipe(writePipe) == 0);
83
84         pid = fork();
85         if (pid == 0)
86         {
87                 close(readPipe[0]);  //close end that parent reads from
88                 close(writePipe[1]); //close end that parent writes to
89
90                 //TODO: Fix possible bug here if the process is already a daemon
91                 assert(writePipe[0] != 0 && readPipe[1] != 1);
92                 dup2(writePipe[0],0); close(writePipe[0]); //pipe end child reads from goes to STDIN
93                 dup2(readPipe[1], 1); close(readPipe[1]); //pipe end child writes to goes to STDOUT
94
95                 //TODO: Somehow force the exec'd process to be unbuffered
96                 setbuf(stdin, NULL); //WARNING: These lines don't appear to have any affect
97                 setbuf(stdout, NULL); //You should add them at the start of the wrapped program.
98                                         //If your wrapped program is not written in C/C++, you will probably have a problem
99                                 
100
101                 if (access(executablePath, X_OK) == 0) //Check we STILL have permissions to start the file
102                 {
103                         execv(executablePath,arguments); ///Replace process with desired executable
104                 }
105                 perror("execv error:\n");
106                 fprintf(stderr, "Program::Program - Could not run program \"%s\"!\n", executablePath);
107                 exit(EXIT_FAILURE); //We will probably have to terminate the whole program if this happens
108         }
109         else
110         {
111                 close(writePipe[0]); //close end that child writes to
112                 close(readPipe[1]); //close end that child reads from
113
114                 input = fdopen(readPipe[0],"r"); output = fdopen(writePipe[1],"w");
115                 setbuf(input, NULL);
116                 setbuf(output, NULL);
117         }
118         
119 }
120
121 /**
122  * Destructor
123  * Writes EOF to the wrapped program and then closes all streams
124  * Kills the wrapped program if it does not exit within 1 second.
125  */
126 Program::~Program()
127 {
128         if (Running()) //Check if the process created is still running...
129         {
130                 //fputc(EOF, output); //If it was, tell it to stop with EOF
131
132                 TimerThread timer(2); //Wait for 2 seconds
133                 timer.Start();          
134                 while (!timer.Finished())
135                 {
136                         if (!Running())
137                         {
138                                 timer.Stop();
139                                 break;
140                         }
141                 }
142                 timer.Stop();
143                 kill(pid, SIGKILL);
144         }
145         if (pid > 0)
146         {
147                 fclose(input);
148                 fclose(output);
149         }
150         
151 }
152
153 /**
154  * Forces the program to pause by sending SIGSTOP
155  * Program can be resumed by calling Continue() (which sends SIGCONT)
156  * @returns true if the program could be paused, false if it couldn't (probably because it wasn't running)
157  */
158 bool Program::Pause()
159 {
160         if (pid > 0 && kill(pid,SIGSTOP) == 0)
161         {
162                 paused = true;
163                 return true;
164         }
165         return false;
166 }
167
168 /**
169  * Causes a paused program to continue
170  * @returns true if the program could be continued, false if it couldn't (probably because it wasn't running)
171  */
172 bool Program::Continue()
173 {
174         if (pid > 0 && kill(pid,SIGCONT) == 0)
175         {
176                 paused = false;
177                 return true;
178         }
179         return false;
180 }
181
182 /**
183  * @returns true iff the program is paused
184  */
185 bool Program::Paused() const
186 {
187         return paused;
188 }
189
190
191 /**
192  * Sends a message to the wrapped AI program
193  * WARNING: Always prints a new line after the message (so don't include a new line)
194  *      This is because everything is always line buffered.
195  * @returns true if the message was successfully sent; false if it was not (ie: the process was not running!)
196  */
197 bool Program::SendMessage(const char * print, ...)
198 {
199         if (!Running()) //Is the process running...
200                 return false; 
201
202         va_list ap;
203         va_start(ap, print);
204
205         if (vfprintf(output, print, ap) < 0 || fprintf(output, "\n") < 0)
206         {
207                 va_end(ap);
208                 return false;
209         }
210         va_end(ap);
211         
212
213
214
215         return true;
216 }
217
218
219 /**
220  * Retrieves a message from the wrapped AI program, waiting a maximum amount of time
221  * @param buffer - C++ string to store the resultant message in
222  * @param timeout - Maximum amount of time to wait before failure. If timeout <= 0, then GetMessage will wait indefinately.
223  * @returns true if the response was recieved within the specified time, false if it was not, or an EOF was recieved, or the process was not running.
224  */
225 bool Program::GetMessage(string & buffer, double timeout)
226 {
227         if (!Running() || timeout == 0)
228                 return false;
229
230         struct timeval tv;
231         fd_set readfds;
232         
233         tv.tv_sec = (int)(timeout);
234         tv.tv_usec = (timeout - (double)((int)timeout)) * 1000000;
235         
236         int fd = fileno(input);
237
238         FD_ZERO(&readfds);
239         FD_SET(fd, &readfds);
240
241         select(fd+1, &readfds, NULL, NULL, &tv);
242
243         if (!FD_ISSET(fd, &readfds))
244                 return false; //Timed out
245         //fprintf(stderr, "Got message!\n");
246         for (char c = fgetc(input); c != '\n' && (int)(c) != EOF; c = fgetc(input))
247         {       
248                 //fprintf(stderr, "%c", c);
249                 buffer += c;
250         }
251         //fprintf(stderr, "%s\n", buffer.c_str());
252         return true;
253
254         /* Old way, using threads, which apparently is terrible
255         assert(&buffer != NULL);
256         GetterThread getterThread(input, buffer);
257         assert(&(getterThread.buffer) != NULL);
258
259         TimerThread timerThread(timeout*1000000);
260
261         getterThread.Start();
262         if (timeout > 0)
263                 timerThread.Start();
264
265         
266         while (!getterThread.Finished())
267         {
268                 if (timeout > 0 && timerThread.Finished())
269                 {
270                         getterThread.Stop();
271                         timerThread.Stop();
272                         return false;
273                 }
274         }
275
276         getterThread.Stop();
277         if (timeout > 0)
278                 timerThread.Stop();
279
280         
281
282         if (buffer.size() == 1 && buffer[0] == EOF)
283                 return false;
284         return true;
285         */
286
287 }
288
289 /**
290  * Returns true iff the process is running
291  * @returns what I just said, fool
292  */
293 bool Program::Running() const
294 {
295         return (pid > 0 && kill(pid,0) == 0);
296 }
297
298
299
300

UCC git Repository :: git.ucc.asn.au