8 #include <boost/regex.hpp>
9 #include <boost/lexical_cast.hpp>
17 RController::RController()
20 this->connected =
false;
22 this->write_pipe = -1;
23 this->cleared =
false;
24 this->temp_filename =
"";
27 RController::~RController()
30 if(temp_filename !=
"")
32 remove(temp_filename.c_str());
33 remove(temp_dir.c_str());
39 bool RController::rProcessStart()
42 int child_read_pipe[2];
43 int child_write_pipe[2];
46 if(pipe(child_read_pipe) < 0)
51 if(pipe(child_write_pipe) < 0)
53 close(child_read_pipe[0]);
54 close(child_read_pipe[1]);
63 cerr <<
"Failed to fork a child process.\n";
72 close(child_read_pipe[1]);
73 dup2(child_read_pipe[0], STDIN_FILENO);
74 close(child_read_pipe[0]);
76 close(child_write_pipe[0]);
77 dup2(child_write_pipe[1], STDOUT_FILENO);
78 close(child_write_pipe[1]);
80 const char * program =
"R";
83 "--no-save",
"--no-restore",
"--quiet",
87 cerr <<
"Failed to execute.\n";
95 close(child_read_pipe[0]);
96 close(child_write_pipe[1]);
97 this->read_pipe = child_write_pipe[0];
98 this->write_pipe = child_read_pipe[1];
99 this->child_pid = pid;
100 this->connected =
true;
108 void RController::rProcessKill()
110 kill(this->child_pid,9);
111 this->connected =
false;
117 bool RController::start()
122 cerr <<
"Failed to create R child process.\n";
131 void RController::stop()
139 string RController::pipeReadAll()
143 memset(buffer, 0,
sizeof (buffer));
150 bytes = read(read_pipe, buffer,
sizeof(buffer));
151 total_bytes += bytes;
154 memset(buffer, 0,
sizeof (buffer));
156 if(bytes <
sizeof(buffer))
161 this->cleared =
true;
165 void RController::pipeWriteCommand(
string command)
168 const char * temp = command.c_str();
169 write(write_pipe,temp,command.length());
170 this->cleared =
false;
173 void RController::sendCommand(
string command,
bool clear)
176 if(clear && !cleared)
184 if(regex_search(command,boost::regex(
"%f")))
186 createTempFilename();
187 command = regex_replace(command,
192 pipeWriteCommand(command);
195 string RController::getResponse()
198 boost::regex prompt_regexp(
"^> $");
200 string result,line,full_response;
208 result = pipeReadAll();
209 full_response += result;
217 temp.getline(buffer,
sizeof(buffer),
'\n');
219 if(regex_search(line,prompt_regexp))
227 return full_response;
231 void RController::createTempFilename()
233 if(temp_filename ==
"")
235 char dir[] =
"/tmp/CEBLXXXXXX";
237 this->temp_dir = dir;
238 this->temp_filename = string(dir) +
"/matrix";
245 string RController::trimResponse(
string response)
247 boost::regex prompt_regexp(
"^> *");
257 temp.getline(buffer,
sizeof(buffer),
'\n');
261 if(!regex_search(line,prompt_regexp))
271 ublas::matrix<double> RController::readMatrixFromTempFile()
273 return cppR::readTable<double>(this->temp_filename);
276 void RController::writeMatrixToTempFile(ublas::matrix<double> mat)
278 createTempFilename();
279 cout << temp_filename <<
"\n";