]> git.tdb.fi Git - builder.git/blob - source/misc.cpp
Replace per-file copyright notices with a single file
[builder.git] / source / misc.cpp
1 #include <sys/wait.h>
2 #include <fcntl.h>
3 #include <cstdlib>
4 #include <cstring>
5 #include <msp/io/print.h>
6 #include "misc.h"
7
8 using namespace std;
9 using namespace Msp;
10
11 string run_command(const StringList &argv, int *status)
12 {
13         int pfd[2];
14         pipe(pfd);
15
16         string result;
17
18         pid_t pid = fork();
19         if(pid==0)
20         {
21                 char *argv_[argv.size()+1];
22
23                 unsigned j = 0;
24                 for(StringList::const_iterator i=argv.begin(); i!=argv.end(); ++i)
25                         argv_[j++] = strdup(i->c_str());
26                 argv_[j] = 0;
27
28                 close(pfd[0]);
29                 dup2(pfd[1], 1);
30                 close(pfd[1]);
31                 int devnull = open("/dev/null", O_WRONLY);
32                 dup2(devnull, 2);
33                 close(devnull);
34
35                 execvp(argv_[0], argv_);
36                 ::exit(1);
37         }
38         else if(pid==-1)
39                 IO::print(IO::cerr, "Failed to execute %s\n", argv.front());
40         else
41         {
42                 close(pfd[1]);
43                 while(1)
44                 {
45                         char buf[1024];
46                         int len = read(pfd[0], buf, sizeof(buf));
47                         if(len<=0)
48                         {
49                                 int s;
50                                 if(waitpid(pid, &s, WNOHANG))
51                                 {
52                                         if(status)
53                                         {
54                                                 if(WIFEXITED(s))
55                                                         *status = WEXITSTATUS(s);
56                                                 else
57                                                         *status = -1;
58                                         }
59                                         break;
60                                 }
61                         }
62                         else
63                                 result.append(buf, len);
64                 }
65                 close(pfd[0]);
66         }
67
68         return result;
69 }
70
71