]> git.tdb.fi Git - builder.git/blob - source/misc.cpp
Use mspio for all I/O operations
[builder.git] / source / misc.cpp
1 /* $Id$
2
3 This file is part of builder
4 Copyright © 2006-2009  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <sys/wait.h>
9 #include <fcntl.h>
10 #include <cstdlib>
11 #include <cstring>
12 #include <msp/io/print.h>
13 #include "misc.h"
14
15 using namespace std;
16 using namespace Msp;
17
18 string run_command(const StringList &argv)
19 {
20         int pfd[2];
21         pipe(pfd);
22
23         string result;
24
25         pid_t pid=fork();
26         if(pid==0)
27         {
28                 char *argv_[argv.size()+1];
29
30                 unsigned j=0;
31                 for(StringList::const_iterator i=argv.begin(); i!=argv.end(); ++i)
32                         argv_[j++]=strdup(i->c_str());
33                 argv_[j]=0;
34
35                 close(pfd[0]);
36                 dup2(pfd[1], 1);
37                 close(pfd[1]);
38                 int devnull=open("/dev/null", O_WRONLY);
39                 dup2(devnull, 2);
40                 close(devnull);
41
42                 execvp(argv_[0], argv_);
43                 ::exit(1);
44         }
45         else if(pid==-1)
46                 IO::print(IO::cerr, "Failed to execute %s\n", argv.front());
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                 close(pfd[0]);
63         }
64
65         return result;
66 }
67
68