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