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