]> git.tdb.fi Git - builder.git/blob - source/misc.cpp
Add comments
[builder.git] / source / misc.cpp
1 #include <iostream>
2 #include <sys/wait.h>
3 #include <msp/iter.h>
4 #include "misc.h"
5
6 using namespace std;
7 using namespace Msp;
8
9 /**
10 Runs a command and returns its output as a string.  The exit status of the
11 command is lost.
12 */
13 string run_command(const StringList &argv)
14 {
15         int pfd[2];
16         pipe(pfd);
17
18         string result;
19
20         pid_t pid=fork();
21         if(pid==0)
22         {
23                 char *argv_[argv.size()+1];
24                 for(CountingIterator<const string, StringList::const_iterator> i=argv.begin(); i!=argv.end(); ++i)
25                         argv_[i.count()]=strdup(i->c_str());
26                 argv_[argv.size()]=0;
27                 close(pfd[0]);
28                 dup2(pfd[1], 1);
29                 dup2(pfd[1], 2);
30                 execvp(argv_[0], argv_);
31                 ::exit(1);
32         }
33         else if(pid==-1)
34                 cerr<<"Failed to execute "<<argv.front()<<'\n';
35         else
36         {
37                 close(pfd[1]);
38                 while(1)
39                 {
40                         char buf[1024];
41                         int len=read(pfd[0], buf, sizeof(buf));
42                         if(len<=0)
43                         {
44                                 if(waitpid(pid, 0, WNOHANG))
45                                         break;
46                         }
47                         else
48                                 result.append(buf, len);
49                 }
50         }
51         
52         return result;
53 }
54
55