make SvnRunner usable as a class

This commit is contained in:
Josh Holtrop 2016-03-15 23:02:05 -04:00
parent 4491e4e22e
commit a8bee35697
3 changed files with 59 additions and 31 deletions

View File

@ -1,12 +1,11 @@
#include "SvnRunner.h" #include "SvnRunner.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/wait.h> #include <sys/wait.h>
void SvnRunner::exec_svn(std::vector<std::string> arguments) SvnRunner::SvnRunner(std::vector<std::string> arguments)
{ {
m_pid = 0;
int fd[2]; int fd[2];
int pipe_rc = pipe(fd); int pipe_rc = pipe(fd);
if (pipe_rc == -1) if (pipe_rc == -1)
@ -14,13 +13,13 @@ void SvnRunner::exec_svn(std::vector<std::string> arguments)
perror("pipe"); perror("pipe");
return; return;
} }
pid_t pid = fork(); m_pid = fork();
if (pid == -1) if (m_pid == -1)
{ {
perror("fork"); perror("fork");
return; return;
} }
if (pid == 0) if (m_pid == 0)
{ {
close(fd[0]); close(fd[0]);
int dup2_rc = dup2(fd[1], STDOUT_FILENO); int dup2_rc = dup2(fd[1], STDOUT_FILENO);
@ -46,28 +45,38 @@ void SvnRunner::exec_svn(std::vector<std::string> arguments)
else else
{ {
close(fd[1]); close(fd[1]);
size_t n = 100; m_n = 100;
char * line = (char *)malloc(n); m_line = (char *)malloc(m_n);
FILE * in = fdopen(fd[0], "r"); m_svn_fh = fdopen(fd[0], "r");
ssize_t getline_rc;
for (;;)
{
getline_rc = getline(&line, &n, in);
if (getline_rc == -1)
break;
printf("Got >%s<\n", line);
} }
fclose(in); }
const char * SvnRunner::get_line()
{
if (m_pid > 0)
{
ssize_t getline_rc = getline(&m_line, &m_n, m_svn_fh);
if (getline_rc == -1)
{
fclose(m_svn_fh);
int status; int status;
int waitpid_rc = waitpid(pid, &status, 0); int waitpid_rc = waitpid(m_pid, &status, 0);
if (waitpid_rc == -1) if (waitpid_rc == -1)
{ {
perror("waitpid"); perror("waitpid");
} }
if (WEXITSTATUS(status) != 0) m_status = WEXITSTATUS(status);
{ free(m_line);
fprintf(stderr, "Warning: svn exit status = %d\n", WEXITSTATUS(status)); m_pid = 0;
return NULL;
} }
free(line); else
{
return m_line;
}
}
else
{
return NULL;
} }
} }

View File

@ -1,8 +1,19 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <unistd.h>
#include <stdio.h>
class SvnRunner class SvnRunner
{ {
public: public:
static void exec_svn(std::vector<std::string> arguments); SvnRunner(std::vector<std::string> arguments);
const char * get_line();
int status() { return m_status; }
protected:
char * m_line;
size_t m_n;
pid_t m_pid;
FILE * m_svn_fh;
int m_status;
}; };

View File

@ -6,5 +6,13 @@ using namespace std;
int main(int argc, char * argv[]) int main(int argc, char * argv[])
{ {
cout << "Hello there." << endl; cout << "Hello there." << endl;
SvnRunner::exec_svn({"ls"}); SvnRunner runner({"ls"});
for(;;)
{
const char * line = runner.get_line();
if (line == NULL)
break;
fprintf(stdout, ">> %s", line);
}
fprintf(stdout, "Exit status: %d\n", runner.status());
} }