xapian-core  1.4.26
runprocess.cc
Go to the documentation of this file.
1 
4 /* Copyright (C) 2003,2006,2007 Olly Betts
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #include <config.h>
22 
23 #include "runprocess.h"
24 #include "stringutils.h"
25 
26 #include <stdio.h>
27 #include <string>
28 
29 #include "safesyswait.h"
30 
31 #ifdef _MSC_VER
32 # define popen _popen
33 # define pclose _pclose
34 #endif
35 
36 using namespace std;
37 
38 string
39 stdout_to_string(const string &cmd)
40 {
41  string out;
42  FILE * fh = popen(cmd.c_str(), "r");
43  if (fh == NULL) throw ReadError();
44  while (!feof(fh)) {
45  char buf[4096];
46  size_t len = fread(buf, 1, 4096, fh);
47  if (ferror(fh)) {
48  (void)pclose(fh);
49  throw ReadError();
50  }
51  out.append(buf, len);
52  }
53  int status = pclose(fh);
54 
55  if (status != 0) {
56  if (WIFEXITED(status) && WEXITSTATUS(status) == 127) {
57  throw NoSuchProgram();
58  }
59  throw ReadError();
60  }
61  while (out.size() > 0 && C_isspace(out[out.size() - 1])) {
62  out.resize(out.size() - 1);
63  }
64  return out;
65 }
run an external process and capture its output in a string.
STL namespace.
Exception thrown if we encounter a read error.
Definition: runprocess.h:27
string stdout_to_string(const string &cmd)
Run command cmd, capture its stdout, and return it as a std::string.
Definition: runprocess.cc:39
bool C_isspace(char ch)
Definition: stringutils.h:208
Exception thrown if the program isn&#39;t found.
Definition: runprocess.h:30
Various handy helpers which std::string really should provide.
include <sys/wait.h>, with portability stuff.