4 #include <msp/fs/dir.h>
5 #include <msp/io/console.h>
6 #include <msp/io/file.h>
7 #include <msp/io/print.h>
8 #include <msp/time/units.h>
9 #include "externaltask.h"
14 ExternalTask::ExternalTask(const vector<string> &a, const FS::Path &wd):
19 stdout_dest(PASSTHROUGH),
20 stderr_dest(PASSTHROUGH),
24 ExternalTask::~ExternalTask()
29 string ExternalTask::get_command() const
32 for(vector<string>::const_iterator i=argv.begin(); i!=argv.end(); ++i)
37 for(string::const_iterator j=i->begin(); j!=i->end(); ++j)
39 if(*j=='"' || *j=='\'' || *j==' ' || *j=='\\' || *j=='&')
48 void ExternalTask::start()
50 if(stdout_dest==CAPTURE || stderr_dest==CAPTURE)
51 capture_pipe = new IO::Pipe;
62 vector<const char *> cargv(argv.size()+1);
63 for(unsigned i=0; i<argv.size(); ++i)
64 cargv[i] = argv[i].c_str();
67 if(stdout_dest==IGNORE || stderr_dest==IGNORE)
69 IO::File devnull("/dev/null", IO::M_WRITE);
70 if(stdout_dest==IGNORE)
71 IO::cout.redirect(devnull);
72 if(stderr_dest==IGNORE)
73 IO::cerr.redirect(devnull);
78 if(stdout_dest==CAPTURE)
79 IO::cout.redirect(*capture_pipe);
80 if(stderr_dest==CAPTURE)
81 IO::cerr.redirect(*capture_pipe);
87 execvp(cargv.front(), const_cast<char *const *>(&cargv.front()));
88 IO::print("Couldn't execute %s\n", argv.front());
93 Task::Status ExternalTask::check()
95 return do_wait(false);
98 Task::Status ExternalTask::wait()
100 return do_wait(true);
103 Task::Status ExternalTask::do_wait(bool block)
108 if(waitpid(pid, &status, (block ? 0 : WNOHANG))==pid)
110 if(WIFEXITED(status))
111 exit_code = WEXITSTATUS(status);
112 else if(WIFSIGNALED(status))
113 exit_code = 256+WTERMSIG(status);
119 // Do this after waiting to avoid a race condition
122 while(IO::poll(*capture_pipe, IO::P_INPUT, Time::zero))
125 unsigned len = capture_pipe->read(buf, sizeof(buf));
126 output.append(buf, len);
135 signal_finished.emit(!exit_code);
138 return exit_code ? ERROR : SUCCESS;
141 void ExternalTask::set_stdout(Destination d)
146 void ExternalTask::set_stderr(Destination d)
151 string ExternalTask::run_and_capture_output(const Arguments &argv, const FS::Path &wd)
153 ExternalTask task(argv, wd);
154 task.set_stdout(CAPTURE);
155 task.set_stderr(IGNORE);
157 if(task.wait()!=SUCCESS)
158 throw runtime_error(format("%s failed", argv.front()));
159 return task.get_output();