]> git.tdb.fi Git - builder.git/blob - source/misc.cpp
37616a95f3dfeba4a5994d6f00eb727f04caaccf
[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 string run_command(const list<string> &argv)
10 {
11         int pfd[2];
12         pipe(pfd);
13
14         string result;
15
16         pid_t pid=fork();
17         if(pid==0)
18         {
19                 char *argv_[argv.size()+1];
20                 for(CountingIterator<const string, list<string>::const_iterator> i=argv.begin(); i!=argv.end(); ++i)
21                         argv_[i.count()]=strdup(i->c_str());
22                 argv_[argv.size()]=0;
23                 close(pfd[0]);
24                 dup2(pfd[1], 1);
25                 dup2(pfd[1], 2);
26                 execvp(argv_[0], argv_);
27                 ::exit(1);
28         }
29         else if(pid==-1)
30                 cerr<<"Failed to execute "<<argv.front()<<'\n';
31         else
32         {
33                 close(pfd[1]);
34                 while(1)
35                 {
36                         char buf[1024];
37                         int len=read(pfd[0], buf, sizeof(buf));
38                         if(len<=0)
39                         {
40                                 if(waitpid(pid, 0, WNOHANG))
41                                         break;
42                         }
43                         else
44                                 result.append(buf, len);
45                 }
46         }
47         
48         return result;
49 }
50
51