program.cpp 4.52 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)
{
Sam Moore's avatar
Sam Moore committed
25
26
	//See if file exists and is executable...
	if (access(executablePath, X_OK) != 0)
27
28
29
30
	{
		pid = -1;
		return;
	}
31
	
Sam Moore's avatar
Sam Moore committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
	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
				

Sam Moore's avatar
Sam Moore committed
53
54
55
56
57
		if (access(executablePath, X_OK) == 0) //Check we STILL have permissions to start the file
			execl(executablePath, executablePath, (char*)(NULL)); ///Replace process with desired executable
		
		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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
	}
	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()
{
78
	if (Running()) //Check if the process created is still running...
Sam Moore's avatar
Sam Moore committed
79
	{
Sam Moore's avatar
Sam Moore committed
80
		//fputc(EOF, output); //If it was, tell it to stop with EOF
81
82
83
84

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





/**
 * 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.
111
 * @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
112
113
114
 */
bool Program::SendMessage(const char * print, ...)
{
115
	if (!Running()) //Is the process running...
Sam Moore's avatar
Sam Moore committed
116
117
118
119
120
		return false; 

	va_list ap;
	va_start(ap, print);

121
122
123
124
125
126
	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
127
128
	

129

Sam Moore's avatar
Sam Moore committed
130
131
132
133
134
135
136
137
138
139
140
141
142

	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)
{
143
	if (!Running())
Sam Moore's avatar
Sam Moore committed
144
145
146
147
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
		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
{
184
	return (pid > 0 && kill(pid,0) == 0);
Sam Moore's avatar
Sam Moore committed
185
186
187
}


188
189