CASM
AClustersApproachtoStatisticalMechanics
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules
Popen.cc
Go to the documentation of this file.
1 #include "casm/system/Popen.hh"
2 #include <stdexcept>
3 
4 namespace CASM {
5 
8  std::function<void(FILE *)> _popen_handler,
9  std::function<void(int)> _pclose_handler,
10  bool _combine_stdout_stderr) :
11  m_popen_handler(_popen_handler),
12  m_pclose_handler(_pclose_handler),
13  m_combine_stdout_stderr(_combine_stdout_stderr) {}
14 
19  void Popen::popen(std::string _command) {
20 
21  m_command = _command;
22 
24  m_command += " 2>&1";
25  }
26 
27  FILE *fp;
28  char path[PATH_MAX];
29 
30  fp = ::popen(m_command.c_str(), "r");
31  m_popen_handler(fp);
32 
33  m_stdout = "";
34  while(fgets(path, PATH_MAX, fp) != nullptr) {
35  m_stdout += path;
36  }
37 
38  m_pclose_result = pclose(fp);
39 
41  }
42 
44  std::string Popen::gets() const {
45  return m_stdout;
46  }
47 
49  void Popen::print(std::ostream &sout) const {
50  sout << m_command << "\n";
51  sout << m_stdout;
52  }
53 
55  int Popen::exit_code() const {
56  return m_pclose_result / 256;
57  }
58 
61  if(fp == nullptr) {
62  throw std::runtime_error("Error: popen failed.");
63  }
64  }
65 
67  void Popen::default_pclose_handler(int status) {
68  if(status == -1) {
69  throw std::runtime_error("Error: pclose failed.");
70  }
71  }
72 
73 }
74 
std::function< void(FILE *)> m_popen_handler
Definition: Popen.hh:44
std::string gets() const
Returns the stdout resulting from the last popen call.
Definition: Popen.cc:44
int m_pclose_result
Definition: Popen.hh:43
void popen(std::string _command)
Execute popen for a given command.
Definition: Popen.cc:19
void print(std::ostream &sout) const
Print the last command executed and the resulting stdout.
Definition: Popen.cc:49
Main CASM namespace.
Definition: complete.cpp:8
std::string m_command
Definition: Popen.hh:41
static void default_pclose_handler(int status)
Default pclose error handler throws std::runtime_error if pclose failed.
Definition: Popen.cc:67
std::function< void(int)> m_pclose_handler
Definition: Popen.hh:45
int exit_code() const
Returns pclose(fp)/256.
Definition: Popen.cc:55
Popen(std::function< void(FILE *)> _popen_handler=Popen::default_popen_handler, std::function< void(int)> _pclose_handler=Popen::default_pclose_handler, bool _combine_stdout_stderr=true)
Construct a Popen object.
Definition: Popen.cc:7
std::string m_stdout
Definition: Popen.hh:42
static void default_popen_handler(FILE *fp)
Default popen error handler throws std::runtime_error if popen failed.
Definition: Popen.cc:60
bool m_combine_stdout_stderr
Definition: Popen.hh:46