program.cpp 4.46 KB
Newer Older
Sam Moore's avatar
Sam Moore committed
1
2
3
4
5
6
7
8
9
10
11
12
#include <sstream>

#include <stdarg.h>

#include <cassert>

#include "thread_util.h"
#include "program.h"


using namespace std;

13

Sam Moore's avatar
Sam Moore committed
14
15
16
17
18
19
20
21
22
23
24
/**
 * Constructor
 * @param executablePath - path to the program that will be run
 *
 * Creates two pipes - one for each direction between the parent process and the AI program
 * Forks the process. 
 *	The child process closes unused sides of the pipe, and then calls exec to replace itself with the AI program
 *	The parent process closes unused sides of the pipe, and sets up member variables - associates streams with the pipe fd's for convenience.
 */
Program::Program(const char * executablePath) : input(NULL), output(NULL), pid(0)
{
25
26
27
28
29
30
31
32
33
34
35
	//See if file exists...
	FILE * file = fopen(executablePath, "r");
	if (file != NULL)
	{
		fclose(file);
	}
	else
	{
		pid = -1;
		return;
	}
36
	
Sam Moore's avatar
Sam Moore committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
	int readPipe[2]; int writePipe[2];
	assert(pipe(readPipe) == 0);
	assert(pipe(writePipe) == 0);

	pid = fork();
	if (pid == 0)
	{
		close(readPipe[0]);  //close end that parent reads from
		close(writePipe[1]); //close end that parent writes to

		//TODO: Fix possible bug here if the process is already a daemon
		assert(writePipe[0] != 0 && readPipe[1] != 1);
		dup2(writePipe[0],0); close(writePipe[0]); //pipe end child reads from goes to STDIN
		dup2(readPipe[1], 1); close(readPipe[1]); //pipe end child writes to goes to STDOUT

		//TODO: Somehow force the exec'd process to be unbuffered
		setbuf(stdin, NULL); //WARNING: These lines don't appear to have any affect
		setbuf(stdout, NULL); //You should add them at the start of the wrapped program.
					//If your wrapped program is not written in C/C++, you will probably have a problem
				


		execl(executablePath, executablePath, (char*)(NULL)); ///Replace process with desired executable
60
61
		//fprintf(stderr, "Program::Program - Could not run program \"%s\"!\n", executablePath);
		//exit(EXIT_FAILURE); //We will probably have to terminate the whole program if this happens
Sam Moore's avatar
Sam Moore committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
	}
	else
	{
		close(writePipe[0]); //close end that child writes to
		close(readPipe[1]); //close end that child reads from

		input = fdopen(readPipe[0],"r"); output = fdopen(writePipe[1],"w");
		setbuf(input, NULL);
		setbuf(output, NULL);
	}
	
}

/**
 * Destructor
 * Writes EOF to the wrapped program and then closes all streams
 * Kills the wrapped program if it does not exit within 1 second.
 */
Program::~Program()
{
82
	if (Running()) //Check if the process created is still running...
Sam Moore's avatar
Sam Moore committed
83
	{
Sam Moore's avatar
Sam Moore committed
84
		//fputc(EOF, output); //If it was, tell it to stop with EOF
85
86
87
88

		TimerThread timer(2); //Wait for 2 seconds
		timer.Start();		
		while (!timer.Finished())
Sam Moore's avatar
Sam Moore committed
89
		{
90
91
92
93
94
			if (!Running())
			{
				timer.Stop();
				break;
			}
Sam Moore's avatar
Sam Moore committed
95
		}
96
97
98
99
100
101
102
		timer.Stop();
		kill(pid, SIGKILL);
	}
	if (pid > 0)
	{
		fclose(input);
		fclose(output);
Sam Moore's avatar
Sam Moore committed
103
104
105
106
107
108
109
110
111
112
113
114
	}
	
}





/**
 * Sends a message to the wrapped AI program
 * WARNING: Always prints a new line after the message (so don't include a new line)
 *	This is because everything is always line buffered.
115
 * @returns true if the message was successfully sent; false if it was not (ie: the process was not running!)
Sam Moore's avatar
Sam Moore committed
116
117
118
 */
bool Program::SendMessage(const char * print, ...)
{
119
	if (!Running()) //Is the process running...
Sam Moore's avatar
Sam Moore committed
120
121
122
123
124
		return false; 

	va_list ap;
	va_start(ap, print);

125
126
127
128
129
130
	if (vfprintf(output, print, ap) < 0 || fprintf(output, "\n") < 0)
	{
		va_end(ap);
		return false;
	}
	va_end(ap);
Sam Moore's avatar
Sam Moore committed
131
132
	

133

Sam Moore's avatar
Sam Moore committed
134
135
136
137
138
139
140
141
142
143
144
145
146

	return true;
}


/**
 * Retrieves a message from the wrapped AI program, waiting a maximum amount of time
 * @param buffer - C++ string to store the resultant message in
 * @param timeout - Maximum amount of time to wait before failure. If timeout <= 0, then GetMessage will wait indefinately.
 * @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.
 */
bool Program::GetMessage(string & buffer, double timeout)
{
147
	if (!Running())
Sam Moore's avatar
Sam Moore committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
		return false;

	assert(&buffer != NULL);
	GetterThread getterThread(input, buffer);
	assert(&(getterThread.buffer) != NULL);
	TimerThread timerThread(timeout*1000000);

	getterThread.Start();
	if (timeout > 0)
		timerThread.Start();

	
	while (!getterThread.Finished())
	{
		if (timeout > 0 && timerThread.Finished())
		{
			getterThread.Stop();
			timerThread.Stop();
			return false;
		}
	}

	getterThread.Stop();
	timerThread.Stop();

	

	if (buffer.size() == 1 && buffer[0] == EOF)
		return false;
	return true;


}

/**
 * Returns true iff the process is running
 * @returns what I just said, fool
 */
bool Program::Running() const
{
188
	return (pid > 0 && kill(pid,0) == 0);
Sam Moore's avatar
Sam Moore committed
189
190
191
}


192
193