]> git.tdb.fi Git - builder.git/blob - source/misc.cpp
Use ExternalTask rather than run_command for running pkg-config
[builder.git] / source / misc.cpp
1 #include <sys/wait.h>
2 #include <fcntl.h>
3 #include <cstdlib>
4 #include <cstring>
5 #include <unistd.h>
6 #include <msp/io/print.h>
7 #include "misc.h"
8
9 using namespace std;
10 using namespace Msp;
11
12 string run_command(const StringList &argv, int *status)
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                 close(pfd[1]);
32                 int devnull = open("/dev/null", O_WRONLY);
33                 dup2(devnull, 2);
34                 close(devnull);
35
36                 execvp(argv_[0], argv_);
37                 ::exit(1);
38         }
39         else if(pid==-1)
40                 IO::print(IO::cerr, "Failed to execute %s\n", argv.front());
41         else
42         {
43                 close(pfd[1]);
44                 while(1)
45                 {
46                         char buf[1024];
47                         int len = read(pfd[0], buf, sizeof(buf));
48                         if(len<=0)
49                         {
50                                 int s;
51                                 if(waitpid(pid, &s, WNOHANG))
52                                 {
53                                         if(status)
54                                         {
55                                                 if(WIFEXITED(s))
56                                                         *status = WEXITSTATUS(s);
57                                                 else
58                                                         *status = -1;
59                                         }
60                                         break;
61                                 }
62                         }
63                         else
64                                 result.append(buf, len);
65                 }
66                 close(pfd[0]);
67         }
68
69         return result;
70 }
71
72