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