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